package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AtomicDouble;
import com.hsmw.api.config.NoRepeatSubmit;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.*;
import com.hsmw.api.exception.ApiException;
import com.hsmw.api.mapper.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.util.SendSmsUtil;
import com.htn.common.core.util.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.DriverDetailVO;
import com.hsmw.domain.vo.GpsInfoEntity;
import com.hsmw.domain.vo.OrderPoolVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.*;


/**
 * @author WD
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwUserDriverService extends BaseService<HsmwUserDriverMapper, HsmwUserDriver> {


	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private    RedisCache redisCache;
	/**
	 *  用户所有的订单的抢单信息，这个对象存储是安全的
	 */
	private static volatile  ConcurrentHashMap<String, List<OrderPoolVO>> orderPool ;

	static {
		orderPool = new ConcurrentHashMap<String, List<OrderPoolVO>>();
	}

	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;

	@Autowired
	private CurrentHsmwUserUtils currentHsmwUserUtils;
	@Autowired
	private HsmwUserMapper hsmwUserMapper;


	public  static  Timer timer;


	@Autowired
	private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;


	@Autowired
	private HsmwOrderService hsmwOrderService;


	@Autowired
	private HsmwVehicleService hsmwVehicleService;

	@Autowired
	private HsmwDriverNewsService hsmwDriverNewsService;


	@Autowired
	private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;


	@Autowired
	private HsmwOrderVehicleRelationMapper hsmwOrderVehicleRelationMapper  ;



	@Autowired
	private HsmwPictureService hsmwPictureService;


	@Autowired
	private HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService;

	@Autowired
	private WebSocket  webSocket;

	@Autowired
	private HsmwPhoneBindService hsmwPhoneBindService;


	@Autowired
	private HsmwGpsService   hsmwGpsService;




	@Autowired
	private HsmwItemService hsmwItemService;



	@Autowired
	private HsmwReportService hsmwReportService;

	@Autowired
	private HsmwBanDriverService hsmwBanDriverService;



	@Autowired
	private HsmwDriverOrderRecordMapper hsmwDriverOrderRecordMapper;


	@Autowired
	private HsmwConstructionPositionService hsmwConstructionPositionService;



	@Autowired
	private HsmwReportRecordService hsmwReportRecordService;

	@Autowired
	private HsmwPointsDetailsService hsmwPointsDetailsService;

	@Autowired
	private HsmwScoringRecordMapper hsmwScoringRecordMapper;

	@Autowired
	private HsmwScoringRecordService hsmwScoringRecordService;

	@Autowired
	private HsmwConcreteInfoMapper hsmwConcreteInfoMapper;

	@Autowired
	private HsmwOrderBalanceMapper hsmwOrderBalanceMapper;

	@Autowired
	private HsmwPushInfoService hsmwPushInfoService;

	@Autowired
	private HsmwExchangeBusService hsmwExchangeBusService;



	@Autowired
	private HsmwDriverUserService hsmwDriverUserService;


	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;

	@Autowired
	private HsmwDriverOrderRecordService hsmwDriverOrderRecordService;

	@Autowired
	private HsmwItemLinkmanMapper hsmwItemLinkmanMapper;

	@Autowired
	private HsmwRunSprintRecordService hsmwRunSprintRecordService;

	@Autowired
	private HsmwReceiveOrderPriceMapper hsmwReceiveOrderPriceMapper;

	@Autowired
	private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;

	@Autowired
	private HsmwLeasingCompanyService hsmwLeasingCompanyService;

	@Autowired
	private HsmwSettlementRecordMapper hsmwSettlementRecordMapper;

	@Autowired
	private HsmwHelpCenterMapper hsmwHelpCenterMapper;

	@Autowired
	private HsmwDriverComplainMapper hsmwDriverComplainMapper;

	@Autowired
	private HsmwDriverCancelOrderRecordService hsmwDriverCancelOrderRecordService;

	@Autowired
	private HsmwOrderMapper hsmwOrderMapper;

	@Autowired
	private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;

	@Autowired
	private HsmwHelpAvaliableInfoMapper hsmwHelpAvaliableInfoMapper;

	@Value(value = "${sms.appKey}")
	private String appKey;
	@Value(value = "${sms.channel}")
	private String channel;
	@Value(value = "${sms.smsSign}")
	private String smsSign;
	@Value(value = "${sms.appId}")
	private int appId;
	@Value(value = "${sms.orderTemplateId}")
	private int orderTemplateId;

	@Value(value = "${sms.orderProcessId}")
	private int orderProcessId;

	@Value(value = "${sms.updateDriverReachTime}")
	private int updateDriverReachTime;



	@Autowired
	private HsmwPumpOperateRecordService hsmwPumpOperateRecordService;

	@Autowired
	private HsmwDriverUserMapper hsmwDriverUserMapper;

	@Autowired
	private HsmwUserDriverService hsmwUserDriverService;

	public IPage<HsmwUserDriver> getHsmwDriverPage(IPage page, HsmwUserDriver hsmwUserDriver) {
		LambdaQueryWrapper<HsmwUserDriver> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsmwUserDriver::getFlag, false);
		IPage ipage = this.baseMapper.selectPage(page, queryWrapper.orderByDesc(HsmwUserDriver::getCreateTime));
		return ipage;
	}



	//待抢单列表
	public List<TaskingOrderVO> taskingOrderList() {
		LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
		HashMap param = new HashMap();
		param.put("userId", hsmwUser.getId());
		return hsmwUserDriverMapper.taskingOrderList(param);
	}

	public DataResponse cancelOrder(OrderQueryParam orderQueryParam) {
		LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
		HsmwUserDriver driver;
		try {
			LambdaQueryWrapper<HsmwUserDriver> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(HsmwUserDriver::getUserId, hsmwUser.getId());
			List<HsmwUserDriver> drivers = list(lambdaQueryWrapper);
			driver = drivers.get(0);
			HsmwOrder order= hsmwOrderService.getById(orderQueryParam.getOrderId());
			order.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
			order.setUpdateTime(LocalDateTime.now());
			order.setUpdateUser(hsmwUser.getId());
			hsmwOrderService.updateById(order);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataResponse(FAIL, "取消订单态异常，请联系管理员！");
		}
		try {

			//司机取消订单 后 司机的工作状态变成
			List<HsmwUserDriver> userDriver = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>().
					eq(HsmwUserDriver::getVehicleId,driver.getVehicleId()));
			if(CollectionUtil.isNotEmpty(userDriver)){
				userDriver.stream().forEach(driverInfo->{
					driverInfo.setWorkStatus(CommonConstants.DRIVER_FREE);
					hsmwUserDriverMapper.updateById(driverInfo);
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new DataResponse(FAIL, "取消订单过程中，修改司机工作状态异常，请联系管理员！");
		}
		try {
			//司机取消订单 后 车辆的工作状态变成空闲中
			HsmwVehicle vehicle2 = hsmwVehicleService.getVehicleById(driver.getVehicleId());
			vehicle2.setId(driver.getVehicleId());
			vehicle2.setWorkStatus(CommonConstants.VEHICLE_FREE);
			hsmwVehicleService.updateById(vehicle2);
			return new DataResponse();
		} catch (Exception e) {
			e.printStackTrace();
			return new DataResponse(FAIL, "取消订单过程中，修改车辆工作状态异常，请联系管理员！");
		}
	}

	public IPage<DriverInfoVO> getBizHsmwDriverPage(IPage page, DriverInfoVO driverInfoVO) {
		IPage<DriverInfoVO> driverInfoVOIPage = hsmwUserDriverMapper.getBizHsmwDriverPage(page, driverInfoVO);
		return driverInfoVOIPage;
	}

	public DriverInfoVO getBizDriverById(String id) {
		DriverInfoVO driverInfoVO = new DriverInfoVO();
		driverInfoVO.setId(id);
		Page page = new Page(1, 20);
		IPage<DriverInfoVO> driverInfoVOIPage = hsmwUserDriverMapper.getBizHsmwDriverPage(page, driverInfoVO);
		return driverInfoVOIPage.getRecords().stream().findFirst().orElse(null);
	}

	public HsmwUserDriver getBizDriverByUserId(String id) {
		LambdaQueryWrapper<HsmwUserDriver> lambdaQueryWrapper = new LambdaQueryWrapper<HsmwUserDriver>();
		lambdaQueryWrapper.eq(HsmwUserDriver::getUserId,id);
		List<HsmwUserDriver> drivers = hsmwUserDriverService.list(lambdaQueryWrapper);
		HsmwUserDriver driver =drivers.stream().findFirst().orElse(null);
		return driver ;
	}


	public DataResponse updateForceManOrderInfo(OrderQueryParam orderQueryParam) {
		try {
			//司机绑定的车辆有没有被抢到。
			LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
			LambdaQueryWrapper<HsmwUserDriver> driverLambdaQueryWrapper = new LambdaQueryWrapper<>();
			driverLambdaQueryWrapper.eq(HsmwUserDriver::getUserId, hsmwUser.getId());
			HsmwUserDriver driver = this.getOne(driverLambdaQueryWrapper);
			LambdaQueryWrapper<HsmwOrderVehicleRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(HsmwOrderVehicleRelation::getOrderId, orderQueryParam.getOrderId());
			lambdaQueryWrapper.eq(HsmwOrderVehicleRelation::getDriverId, driver.getId());
			HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getOne(lambdaQueryWrapper);
			if (OrderStatusEnum.COMPLETED.getValue().equals(orderQueryParam.getStatus())) {
				HsmwOrder order = new HsmwOrder();
				order.setOrderStatus(orderQueryParam.getStatus());
				order.setId(orderQueryParam.getOrderId());
				order.setForemanVolume(orderQueryParam.getForemanVolume());
				hsmwOrderService.updateById(order);
			}
			return new DataResponse();
		}catch (Exception e){
			return new DataResponse(FAIL, "更新订单的状态失败，请联系系统管理员！");
		}
	}



	/**
	 * 抢单结果接口
	 *
	 * @param
	 * @return
	 */
	public  DataResponse getGrabbingResult(OrderQueryParam orderQueryParam) throws Exception {
		List<HsmwOrder> relation = hsmwOrderService.list(
						Wrappers.lambdaQuery(HsmwOrder.class).
								eq(HsmwOrder::getId,orderQueryParam.getOrderId())
								.eq(HsmwOrder::getVehicleId,orderQueryParam.getVehicleId()));
		HashMap result = new HashMap();
		if(StringUtils.isNotNull(relation)){
				result.put("status",3);
		}else{
			result.put("status",4);
		}
		return new DataResponse(result);

	}


	public DataResponse saveOrUpdateHsmwDriver(DriverInfoVO driverInfoVO) {
		if (StrUtil.isBlank(driverInfoVO.getId())) {
			HsmwUser hsmwUser = hsmwUserMapper.selectOne(Wrappers.lambdaQuery(HsmwUser.class).eq(HsmwUser::getUsername, driverInfoVO.getUsername()));
			if(hsmwUser!=null&&!hsmwUser.getType().equals(CommonConstants.UserRole.DRIVER.name())){
				throw new ApiException(CommonConstants.ResponseStatus.USER_IS_EXIST);
			}
			if (hsmwUser == null) {
				hsmwUser = new HsmwUser();
				hsmwUser.setFlag(false);
				hsmwUser.setUsername(driverInfoVO.getUsername());
				hsmwUser.setType(CommonConstants.UserRole.DRIVER.name());
				hsmwUser.setName(driverInfoVO.getName());
				hsmwUser.setEnabled(true);
				hsmwUser.setLastLoginTime(LocalDateTime.now());
				hsmwUserMapper.insert(hsmwUser);
			}
			HsmwUserDriver hsmwUserDriver = hsmwUserDriverMapper.selectOne(Wrappers.lambdaQuery(HsmwUserDriver.class).eq(HsmwUserDriver::getUserId, hsmwUser.getId()));
			if (hsmwUserDriver == null) {
				driverInfoVO.setFlag(false);
				driverInfoVO.setWorkStatus(CommonConstants.DRIVER_FREE);
				driverInfoVO.setUserId(hsmwUser.getId());
				hsmwUserDriverMapper.insert(driverInfoVO);
			} else {
				throw new ApiException(CommonConstants.ResponseStatus.DRIVER_IS_EXIST);
			}
		} else {
			HsmwUser hsmwUser = hsmwUserMapper.selectOne(Wrappers.lambdaQuery(HsmwUser.class).eq(HsmwUser::getId, driverInfoVO.getUserId()));
			hsmwUser.setUsername(driverInfoVO.getUsername());
			hsmwUser.setName(driverInfoVO.getName());
			hsmwUserMapper.updateById(hsmwUser);
			HsmwVehicle hsmwVehicle = hsmwVehicleService.getById(driverInfoVO.getVehicleId());
			if(StringUtils.isNotNull(hsmwVehicle)){

				Integer count = hsmwUserDriverMapper.selectCount(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, hsmwVehicle.getId()));
				int maxCount = Integer.parseInt(hsmwVehicle.getMaxDriverNumber());
				if(count >= maxCount){
					return new DataResponse(FAIL,"司机超出绑定数量");
				}
			}
			hsmwUserDriverMapper.updateById(driverInfoVO);
		}
		return new DataResponse(SUCCESS);
	}

	public  boolean checkIfExists(List<OrderPoolVO> list,String userId){
		boolean flag=false;
		if(StringUtils.isListNull(list)){
			return false;
		}else{
			for(OrderPoolVO vo :list){
				if(vo.getUserId().equals(userId)){
					flag = true;
					break;
				}
			}
		}
		return flag;
	}


	public Timer getTimerEntity(){
		return new Timer();
	}



	//保存司机提交问题信息
    public void saveProblemInfo(SubmitProblemVO submitProblemVO) {
		if(StringUtils.isListNotNull(submitProblemVO.getPicList())){
			List<HsmwPicture>  pictures = new ArrayList<>();
			List<HashMap>  picList=submitProblemVO.getPicList();
			if(null!= picList && picList.size()>0){
				for(HashMap<String,String> pic :picList){
					HsmwPicture temp = new HsmwPicture();
					temp.setPicPath(pic.get("picPath"));
					temp.setPicRealPath(pic.get("realPath"));
					temp.setOrderId(submitProblemVO.getOrderId());
					temp.setCreateTime(LocalDateTime.now());
					temp.setPicType(PicTypeEnum.DRIVER_PROBLEM.getValue());
					pictures.add(temp);
				}
			}
			hsmwPictureService.saveBatch(pictures);
		}
		//更新子订单信息中的 问题详情和语音详情
		HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(submitProblemVO.getOrderVehicleRelationId());
		relation.setProblemInfo(submitProblemVO.getProblemInfo());
		relation.setProblemAudioUrl(submitProblemVO.getProblemAudioUrl());
		relation.setProblemAudioId(submitProblemVO.getProblemAudioId());
		relation.setOrderStatus(ChildOrderStatusEnum.UNDERREVIEW.getValue());
		relation.setOrderStatusBefore(submitProblemVO.getOrderStatusBefore());
		hsmwOrderVehicleRelationService.updateById(relation);
	}

	//保存工长提交问题信息
	public void saveForemanProblemInfo(SubmitProblemVO submitProblemVO) {
		if(StringUtils.isListNotNull(submitProblemVO.getPicList())){
			List<HsmwPicture>  pictures = new ArrayList<>();
			List<HashMap>  picList=submitProblemVO.getPicList();
			if(null!= picList && picList.size()>0){
				for(HashMap<String,String> pic :picList){
					HsmwPicture temp = new HsmwPicture();
					temp.setPicPath(pic.get("picPath"));
					temp.setPicRealPath(pic.get("realPath"));
					temp.setOrderId(submitProblemVO.getOrderId());
					temp.setCreateTime(LocalDateTime.now());
					temp.setPicType(PicTypeEnum.FOREMAN_PROBLEM.getValue());
					pictures.add(temp);
				}
			}
			hsmwPictureService.saveBatch(pictures);
		}
		//更新子订单信息中的 问题详情和语音详情
		HsmwOrder relation = hsmwOrderService.getById(submitProblemVO.getOrderId());
		relation.setProblemInfo(submitProblemVO.getProblemInfo());
		relation.setProblemAudioUrl(submitProblemVO.getProblemAudioUrl());
		relation.setProblemAudioId(submitProblemVO.getProblemAudioId());
		//relation.setOrderStatus(MainOrderStatusEnum.ENDED.getValue());
		hsmwOrderService.updateById(relation);
	}
	//更新子订单的状态
	@Transactional
	public DataResponse updateOrderStatusInfo(OrderQueryParam orderQueryParam) {
		try {
			HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(orderQueryParam.getOrderVehicleRelationId());
			String status1 = ChildOrderStatusEnum.STARTUP.getValue();
			String status2 = orderQueryParam.getStatus();
			System.out.println(status1.equals(status2));
			HsmwOrder order = hsmwOrderService.getById(orderQueryParam.getOrderId());
			HsmwHtnUser foremanUser = hsmwHtnUserService.getById(order.getCreateUser());
			//当前登陆人信息
			LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
			//推送 工长信息变化
			WXPushVO vo = new WXPushVO();
			vo.setOrderId(orderQueryParam.getOrderId());
			vo.setConstructionAddress(order.getItemPositionDetail());
			vo.setVehicleNums(relation.getVehicleNum());
			vo.setArriveTime(order.getReachTime());
			vo.setConstructionPosition(order.getConstructionPosition());
			HsmwHtnUser foremanuser = hsmwHtnUserService.getById(order.getCreateUser());
			vo.setOpenId(foremanuser.getOpenId());
			vo.setTemplateId(CommonConstants.WX_FOREMEN_TEMP_ID);
			//司机 右滑 出发
			if (ChildOrderStatusEnum.STARTUP.getValue().equals(orderQueryParam.getStatus())) {
				if(!ChildOrderStatusEnum.RECEIVED.getValue().equals(relation.getOrderStatus())){
					return  new DataResponse(CommonConstants.ResponseStatus.UPDATE_FAIL,"您的订单状态已经改变，请刷新页面！");
				}
				relation.setSetoutTime(LocalDateTime.now());
				relation.setOrderStatus(ChildOrderStatusEnum.STARTUP.getValue());
				String vehicleId = relation.getVehicleId();
				HsmwVehicle vehicle = hsmwVehicleService.getById(vehicleId);

				String vehicleLocalteInfo = null;
				String nameByGps = null;
				if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
					GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
					if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
						vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
					}
					if(StringUtils.isNotBlank(vehicleLocalteInfo)){
						nameByGps = GaoDeInfoUtils.gaodeGetNameByGps(vehicleLocalteInfo);
					}
				}

				if(StringUtils.isNotBlank(orderQueryParam.getCurrentLocation()) && !StringUtils.equals("0.0,0.0",orderQueryParam.getCurrentLocation())){
					relation.setSetoutLocation(orderQueryParam.getCurrentLocation());
				}else {
					relation.setSetoutLocation(vehicleLocalteInfo);
				}

				if(StringUtils.isNotBlank(orderQueryParam.getCurrentLocationName())){
					relation.setSetoutLocationName(orderQueryParam.getCurrentLocationName());
				}else {
					relation.setSetoutLocationName(nameByGps);
				}
				vo.setMainTitle(PushOrderStatusEnum.STARTUP.getName());
				HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
				record.setOrderId(order.getId());
				record.setVehicleNum(relation.getVehicleNum());
				record.setRequestId(relation.getOrderVehicleRequestId());
				record.setRelationId(orderQueryParam.getOrderVehicleRelationId());
				record.setCreateTime(LocalDateTime.now());
				record.setOrderStatus(PumpOrderStatusEnum.STARTUP.getValue());
				record.setOperContent("确认出发 出发位置为"+(StringUtils.isNotBlank(orderQueryParam.getCurrentLocationName())?orderQueryParam.getCurrentLocationName():nameByGps));
				hsmwPumpOperateRecordService.save(record);
				//进行推送和存入系统消息
				String message = "泵车"+relation.getVehicleNum()+"已出发前往工地，点击查看车辆位置信息";
				String  foremanUserId = order.getCreateUser();
				String  foremanUsername = foremanUser.getUsername();
				//新增系统消息
				HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				hsmwDriverNews.setUserId(foremanUserId);
				hsmwDriverNews.setMessage(message);
				hsmwDriverNews.setAlreadyRead("0");
				hsmwDriverNewsService.save(hsmwDriverNews);
				WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
				webSocketReturnVO.setRelationId(relation.getId());
				TencentPushUtils.selfrunCanCelMsg(message,foremanUsername,"has_new_message",webSocketReturnVO);
				//TencentPushUtils.selfrunMsg(message,foremanUsername,"has_new_message");

			}
			//司机 右滑 到达
			if (ChildOrderStatusEnum.ARRIVED.getValue().equals(orderQueryParam.getStatus())) {
				if(!ChildOrderStatusEnum.STARTUP.getValue().equals(relation.getOrderStatus())){
					return  new DataResponse(CommonConstants.ResponseStatus.UPDATE_FAIL,"您的订单状态已经改变，请刷新页面！");
				}
				String key = "vehicle:automatic:"+relation.getVehicleId();
				if(StringUtils.isNotBlank(orderQueryParam.getAutomatic()) && StringUtils.equals("1",orderQueryParam.getAutomatic())){
					redisTemplate.opsForValue().set(key,relation.getVehicleId(), 1, TimeUnit.HOURS);
				}

				relation.setReachTime(LocalDateTime.now());
				relation.setOrderStatus(ChildOrderStatusEnum.ARRIVED.getValue());
				relation.setStartWorkTime(LocalDateTime.now());
				vo.setMainTitle(PushOrderStatusEnum.ARRIVED.getName());

				HsmwPushInfo pushInfo = hsmwPushInfoService.getOne(new LambdaQueryWrapper<HsmwPushInfo>().eq(HsmwPushInfo::getRelationId, relation.getId()).eq(HsmwPushInfo::getStatus, "0").eq(HsmwPushInfo::getType,"UPDATE_TIME"));
				if(StringUtils.isNotNull(pushInfo)){
					pushInfo.setStatus("1");
					hsmwPushInfoService.updateById(pushInfo);
				}

				//
				//如果 迟到 小于30分钟 -10
				//小于30 -60     -20 分
				//1小时-2小时     -30
				//2小时以上       -50
				LocalDateTime reachTime = order.getReachTime();
				int subScore = 0;
				if(reachTime.isBefore(LocalDateTime.now())) {
					subScore = -5;
					List<HsmwUserDriver> drivers = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
							.eq(HsmwUserDriver::getVehicleId, relation.getVehicleId()));
					if (CollectionUtil.isNotEmpty(drivers)) {
						int finalSubScore = subScore;
						List<HsmwScoringRecord> hsmwScoringRecords = new ArrayList<>();
						drivers.stream().forEach(driver -> {
							HsmwScoringRecord hsmwScoringRecord = new HsmwScoringRecord();
							hsmwScoringRecord.setInitialScore(driver.getScore());
							String newScore = String.valueOf(Integer.parseInt(driver.getScore()) + finalSubScore);
							driver.setScore(newScore);
							hsmwUserDriverService.updateById(driver);
							//  -5 分
							hsmwScoringRecord.setDriverId(driver.getId());
							hsmwScoringRecord.setEndScore(driver.getScore());
							hsmwScoringRecord.setFluctuateScore("-5");
							hsmwScoringRecord.setRemark("迟到");
							hsmwScoringRecords.add(hsmwScoringRecord);
						});
						hsmwScoringRecordService.saveBatch(hsmwScoringRecords);
					}
				}

				HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
				record.setOrderId(order.getId());
				record.setVehicleNum(relation.getVehicleNum());
				record.setRelationId(orderQueryParam.getOrderVehicleRelationId());
				record.setCreateTime(LocalDateTime.now());
				record.setRequestId(relation.getOrderVehicleRequestId());
				record.setOrderStatus(PumpOrderStatusEnum.STARTUP.getValue());
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
				HashMap param = new HashMap();
				param.put("device_id",relation.getImeiNum());
				param.put("begin_time",dtf.format(relation.getSetoutTime()));
				param.put("end_time",dtf.format(LocalDateTime.now()));
				JSONObject result = GaoDeInfoUtils.getRecenttravel(param);
				Integer travelMileage = result.getInteger("travelMileage");
				java.time.Duration duration = java.time.Duration.between(relation.getSetoutTime(),  LocalDateTime.now() );
				Long totalTime = duration.toMillis();
				Long seconds = totalTime/1000;
				Long  hour = seconds/3600;
				Long min = (seconds%3600)/60;
				record.setOperContent("确认到达 行驶"+travelMileage+"公里 用时" +hour+"小时"+min+"分钟" );
				hsmwPumpOperateRecordService.save(record);
			/*	if(CommonConstants.NO.equals(order.getNoticeFlag())){
					SendSmsUtil.sendOrderCoIdentifyCode(appId, appKey,orderProcessId, smsSign, order.getCreateUserTel(), order.getIdentityNum());
					HsmwOrder order1 = new HsmwOrder();
					order1.setId(orderQueryParam.getOrderId());
					order1.setNoticeFlag(CommonConstants.YES);
					hsmwOrderService.updateById(order1);
				}*/
				//进行推送和存入系统消息
				String message = "泵车"+relation.getVehicleNum()+"已到达工地,请及时取得联系";
				String  foremanUserId = order.getCreateUser();
				String  foremanUsername = foremanUser.getUsername();
				//新增系统消息
				HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				hsmwDriverNews.setUserId(foremanUserId);
				hsmwDriverNews.setMessage(message);
				hsmwDriverNews.setAlreadyRead("0");
				hsmwDriverNewsService.save(hsmwDriverNews);
				WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
				webSocketReturnVO.setRelationId(relation.getId());
				TencentPushUtils.selfrunCanCelMsg(message,foremanUsername,"has_new_message",webSocketReturnVO);
				//TencentPushUtils.selfrunMsg(message,foremanUsername,"has_new_message");
			}
			//司机  工作状态变为逻辑完成
			if (ChildOrderStatusEnum.WORKING.getValue().equals(orderQueryParam.getStatus())) {
				if(!ChildOrderStatusEnum.ARRIVED.getValue().equals(relation.getOrderStatus())){
					return  new DataResponse(CommonConstants.ResponseStatus.UPDATE_FAIL,"您的订单状态已经改变，请刷新页面！");
				}
				relation.setEndTime(LocalDateTime.now());
				relation.setOrderStatus(orderQueryParam.getStatus());

				/*List<HsmwUserDriver> driverss = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
						.eq(HsmwUserDriver::getVehicleId, relation.getVehicleId()).eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));

				List<HsmwDriverCancelOrderRecord> records = new ArrayList<>();
				for (HsmwUserDriver userDriver : driverss) {

					HsmwDriverCancelOrderRecord record = new HsmwDriverCancelOrderRecord();
					HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(userDriver.getUserId());
					if(hsmwDriverUser != null && StringUtils.isNotBlank(hsmwDriverUser.getName()) && StringUtils.isNotBlank(hsmwDriverUser.getUsername())){
						record.setDriverUsername(hsmwDriverUser.getUsername());
						record.setDriverName(hsmwDriverUser.getName());
					}
					record.setDriverId(userDriver.getId());
					record.setOrderId(relation.getOrderId());
					record.setVehicleNum(relation.getVehicleNum());
					record.setVehicleId(relation.getVehicleId());
					record.setRequestId(relation.getOrderVehicleRequestId());
					record.setOrderStatus(ChildOrderStatusEnum.COMPLETED.getValue());
					record.setRelationId(relation.getId());
					record.setItemName(order.getItemName());
					record.setItemPosition(order.getItemPosition());
					record.setVehicleId(relation.getVehicleId());
					record.setVehicleId(userDriver.getVehicleId());
					record.setConstructionPosition(order.getConstructionPosition());
					records.add(record);
				}
				hsmwDriverCancelOrderRecordService.saveBatch(records);*/
				//TencentPushUtils.selfrunMsg(message,foremanUsername,"has_new_message");
			}
			//司机  实际完成
			if (ChildOrderStatusEnum.COMPLETED.getValue().equals(orderQueryParam.getStatus())) {
				if(!ChildOrderStatusEnum.ARRIVED.getValue().equals(relation.getOrderStatus()) && !ChildOrderStatusEnum.UNDERREVIEW.getValue().equals(relation.getOrderStatus()) && !ChildOrderStatusEnum.WORKING.getValue().equals(relation.getOrderStatus())){
					return  new DataResponse(CommonConstants.ResponseStatus.UPDATE_FAIL,"您的订单状态已经改变，请刷新页面！");
				}
				List<HsmwDriverOrderRecord> hsmwDriverOrderRecords = hsmwDriverOrderRecordMapper.selectList(new LambdaQueryWrapper<HsmwDriverOrderRecord>().eq(HsmwDriverOrderRecord::getRelationId,relation.getId()));
				if(CollectionUtil.isNotEmpty(hsmwDriverOrderRecords)){
					return  new DataResponse("请勿重复提交！");
				}
				String settlementVolume ="";
				relation.setOrderStatus(ChildOrderStatusEnum.COMPLETED.getValue());
				relation.setDriverVolume(orderQueryParam.getDriverVolume());
				relation.setProblemAudioId(orderQueryParam.getRemarkAudioId());
				relation.setProblemAudioUrl(orderQueryParam.getRemarkAudioUrl());
				relation.setVehicleWorkStatus(CommonConstants.VEHICLE_FREE);
				relation.setRemark(orderQueryParam.getRemark());
				relation.setChassisKilometers(orderQueryParam.getChassisKilometers());
				relation.setMovePumpCount(orderQueryParam.getMovePumpCount());
				relation.setRemarkAudioUrl(orderQueryParam.getRemarkAudioUrl());
				//解散群组
				hsmwOrderService.destoryGroup(orderQueryParam.getOrderVehicleRelationId());
				//保存图片
				if(StringUtils.isListNotNull(orderQueryParam.getPicList())){
					List<HsmwPicture>  pictures = new ArrayList<>();
					List<HashMap>  picList=orderQueryParam.getPicList();
					if(null!= picList && picList.size()>0){
						for(HashMap<String,String> pic :picList){
							HsmwPicture temp = new HsmwPicture();
							temp.setPicPath(pic.get("picPath"));
							temp.setPicRealPath(pic.get("realPath"));
							temp.setOrderId(orderQueryParam.getOrderId());
							temp.setCreateTime(LocalDateTime.now());
							temp.setPicType(PicTypeEnum.DRIVER_COMPLETE.getValue());
							pictures.add(temp);
						}
					}
					hsmwPictureService.saveBatch(pictures);
				}
				//司机完成   则 将 车辆状态改为 空闲中
				HsmwVehicle  vehicle = hsmwVehicleService.getVehicleById(relation.getVehicleId());
				vehicle.setId(relation.getVehicleId());
				vehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
				hsmwVehicleService.updateById(vehicle);
				vo.setMainTitle(PushOrderStatusEnum.COMPLETED.getName());
				//司机完成工作以后查询 是否有符合该司机的未接单完的订单需求。
				//hsmwOrderService.publishOrderToAUser(driver);

				HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
				record.setOrderId(order.getId());
				record.setVehicleNum(relation.getVehicleNum());
				record.setCreateTime(LocalDateTime.now());
				record.setRequestId(relation.getOrderVehicleRequestId());
				record.setRelationId(orderQueryParam.getOrderVehicleRelationId());
				record.setOrderStatus(PumpOrderStatusEnum.COMPLETED.getValue());
				record.setOperContent("确认完成 完成方量"+ orderQueryParam.getDriverVolume() +"挪泵"+orderQueryParam.getMovePumpCount()+"次"
						+"地盘公里数"+orderQueryParam.getChassisKilometers()+"公里" );
				hsmwPumpOperateRecordService.save(record);
				//要求到达时间
				LocalDateTime reachTime = order.getReachTime();
				//实际到达时间
				LocalDateTime realReachTime = relation.getReachTime();
				//结束时间
				LocalDateTime endTime = relation.getEndTime();
				if(endTime == null){
					endTime = LocalDateTime.now();
					relation.setEndTime(endTime);
				}
				//结算记录表
				HsmwOrderBalance hsmwOrderBalance = new HsmwOrderBalance();
				// 司机方量
				Double driverVolume = Double.valueOf(relation.getDriverVolume());

				LocalDateTime startWorkTime = null;
				Double workTime = 0.0;
				Double formulaTime = 0.0;
				List<HsmwConstructionPosition> positions = hsmwConstructionPositionService.list(new LambdaQueryWrapper<HsmwConstructionPosition>().eq(HsmwConstructionPosition::getOrderId, orderQueryParam.getOrderId()));
				String positionName = "";
				if(CollectionUtil.isNotEmpty(positions)){
					for (HsmwConstructionPosition position : positions) {
						if(StringUtils.isNotBlank(position.getPosition())){
							positionName += position.getPosition()+",";
						}
					}
				}

				List<HsmwRunSprintRecord> runSprintRecords = new ArrayList<>();

				List<HsmwUserDriver> driverss = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
						.eq(HsmwUserDriver::getVehicleId, relation.getVehicleId()).eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
				if(StringUtils.isNotBlank(driverss.get(0).getOwnCompanyId())){
					HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(driverss.get(0).getOwnCompanyId());

					if(StringUtils.isNotNull(company)){
						// 当前司机时天津邵濮集团
						if(StringUtils.equals("天津邵濮集团",company.getName())){
							//实际到达时间小于要求到达时间 工作时间为：要求到达时间后的两个小时
							if(realReachTime != null){
								if(realReachTime.isBefore(reachTime) || realReachTime.equals(reachTime)){
									startWorkTime = (reachTime.plusHours(2));
									// 司机提交的方量不为0 在进行计算结算方量  为0 则结算放量也为0
									if(driverVolume != 0.0){
										if(endTime != null){
											Long endTimeSecond  = endTime.toEpochSecond(ZoneOffset.of("+8"));
											Long reachTimeSecond  = startWorkTime.toEpochSecond(ZoneOffset.of("+8"));
											Double hours = 0.0;
											if((endTimeSecond-reachTimeSecond)%3600>0){
												BigDecimal bd = new BigDecimal((endTimeSecond - reachTimeSecond));
												bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
												BigDecimal divide = bd.divide(new BigDecimal("3600"), BigDecimal.ROUND_HALF_UP);
												long value = (endTimeSecond - reachTimeSecond) / 3600;
												BigDecimal subtract = divide.subtract(new BigDecimal(value));
												//hours = ( / 3600) + 1;
												if(subtract.compareTo(new BigDecimal("0.5")) == 1){
													hours = ((endTimeSecond - reachTimeSecond) / 3600) + 1.0;
												}else {
													hours = ((endTimeSecond - reachTimeSecond) / 3600) + 0.5;
												}
											}else {
												hours = ((endTimeSecond - reachTimeSecond) / 3600.00);
											}
											workTime = hours;
											Long forTime = startWorkTime.toEpochSecond(ZoneOffset.of("+8"));
											Double forHours = 0.0;
											if((endTimeSecond - forTime)%3600 > 0){
												BigDecimal bd = new BigDecimal((endTimeSecond - forTime));
												bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
												BigDecimal divide = bd.divide(new BigDecimal("3600"), BigDecimal.ROUND_HALF_UP);
												long value = (endTimeSecond - forTime) / 3600;
												BigDecimal subtract = divide.subtract(new BigDecimal(value));
												//hours = ( / 3600) + 1;
												if(subtract.compareTo(new BigDecimal("0.5")) == 1){
													forHours = ((endTimeSecond - reachTimeSecond) / 3600) + 1.0;
												}else {
													forHours = ((endTimeSecond - reachTimeSecond) / 3600) + 0.5;
												}

											}else {
												forHours = ((endTimeSecond - forTime) / 3600.0);
											}
											formulaTime = forHours;
											if(hours > 10){
												Double aLong = 100.0;
												aLong = aLong + (hours - 10)*10;
												if(aLong > driverVolume){
													relation.setSettlementVolume(String.valueOf(aLong));
													settlementVolume=String.valueOf(aLong);
												}else {
													relation.setSettlementVolume(String.valueOf(driverVolume));
													settlementVolume=String.valueOf(driverVolume);
												}
											}else {
												Long aLong = 100L;
												if(aLong > driverVolume){
													relation.setSettlementVolume(String.valueOf(aLong));
													settlementVolume=String.valueOf(aLong);
												}else {
													relation.setSettlementVolume(String.valueOf(driverVolume));
													settlementVolume=String.valueOf(driverVolume);
												}
											}
										}
									}else {
										relation.setSetoutLocation("0");
										settlementVolume="0";
										hsmwOrderBalance.setRunCount("1");
									}
								}else {
									startWorkTime = (realReachTime.plusHours(2));
									//反之，为实际到达时间后两个小时
									//结束时间 减去 上述开始时间 如果大于10小时 如：十三个小时 一个小时保底为 10，不满一个小时按照一个小时计算
									if(driverVolume != 0){
										if(endTime != null){
											Long endTimeSecond  = endTime.toEpochSecond(ZoneOffset.of("+8"));
											Long realReachTimeSecond  = startWorkTime.toEpochSecond(ZoneOffset.of("+8"));
											Double hours = 0.0;
											if((endTimeSecond-realReachTimeSecond)%3600>0){
												BigDecimal bd = new BigDecimal((endTimeSecond - realReachTimeSecond));
												bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
												BigDecimal divide = bd.divide(new BigDecimal("3600"), BigDecimal.ROUND_HALF_UP);
												long value = (endTimeSecond - realReachTimeSecond) / 3600;
												BigDecimal subtract = divide.subtract(new BigDecimal(value));
												//hours = ( / 3600) + 1;
												if(subtract.compareTo(new BigDecimal("0.5")) == 1){
													hours = ((endTimeSecond - realReachTimeSecond) / 3600) + 1.0;
												}else {
													hours = ((endTimeSecond - realReachTimeSecond) / 3600) + 0.5;
												}
											}else {
												hours = ((endTimeSecond - realReachTimeSecond) / 3600.0);
											}
											workTime = hours;
											Long forTime = startWorkTime.toEpochSecond(ZoneOffset.of("+8"));
											Double forHours = 0.0;
											if((endTimeSecond - forTime)%3600 > 0){
												BigDecimal bd = new BigDecimal((endTimeSecond - forTime));
												bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
												BigDecimal divide = bd.divide(new BigDecimal("3600"), BigDecimal.ROUND_HALF_UP);
												long value = (endTimeSecond - forTime) / 3600;
												BigDecimal subtract = divide.subtract(new BigDecimal(value));
												//hours = ( / 3600) + 1;
												if(subtract.compareTo(new BigDecimal("0.5")) == 1){
													forHours = ((endTimeSecond - forTime) / 3600) + 1.0;
												}else {
													forHours = ((endTimeSecond - forTime) / 3600) + 0.5;
												}
											}else {
												forHours = ((endTimeSecond - forTime) / 3600.0);
											}
											formulaTime = forHours;
											if(hours > 10){
												Double aLong = 100.0;
												aLong = aLong + (hours - 10)*10;
												if(aLong > driverVolume){
													relation.setSettlementVolume(String.valueOf(aLong));
													settlementVolume=String.valueOf(aLong);
												}else {
													relation.setSettlementVolume(String.valueOf(driverVolume));
													settlementVolume=String.valueOf(driverVolume);
												}
											}else {
												Long aLong = 100L;
												if(aLong > driverVolume){
													relation.setSettlementVolume(String.valueOf(aLong));
													settlementVolume=String.valueOf(aLong);
												}else {
													relation.setSettlementVolume(String.valueOf(driverVolume));
													settlementVolume=String.valueOf(driverVolume);
												}
											}
										}else {
											relation.setSetoutLocation("0");
											settlementVolume="0";
										}
									}else {
										relation.setSettlementVolume("0");
										settlementVolume="0";
										hsmwOrderBalance.setRunCount("1");
									}
								}
							}else {
								relation.setSettlementVolume("0");
								settlementVolume="0";
							}

							if(workTime < 0){
								workTime = 0.0;
							}
							workTime = workTime+2;
						}else {
							// 其他公司
							Long endTimeSecond  = endTime.toEpochSecond(ZoneOffset.of("+8"));
							Long reachTimeSecond  = realReachTime.toEpochSecond(ZoneOffset.of("+8"));
							settlementVolume= relation.getDriverVolume();
							double value = ((endTimeSecond - reachTimeSecond) / 3600);
							workTime = value;
						}
					}
				}

				List<HsmwDriverOrderRecord> records = new ArrayList<>();
				List<HsmwScoringRecord> hsmwScoringRecords = new ArrayList<>();
				String userName = "";
				String vehicleId = driverss.get(0).getVehicleId();
				HsmwVehicle hsmwVehicle = hsmwVehicleService.getById(vehicleId);
				for (HsmwUserDriver driver : driverss) {

					HsmwDriverUser driverUser = hsmwDriverUserService.getById(driver.getUserId());
					if(driverVolume == 0.0){
						HsmwRunSprintRecord hsmwRunSprintRecord = new HsmwRunSprintRecord();
						hsmwRunSprintRecord.setOrderId(relation.getOrderId());
						hsmwRunSprintRecord.setRequestId(relation.getOrderVehicleRequestId());
						hsmwRunSprintRecord.setRelationId(relation.getId());
						hsmwRunSprintRecord.setFlag("2");
						hsmwRunSprintRecord.setDriverId(driver.getId());
						runSprintRecords.add(hsmwRunSprintRecord);

						WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
						webSocketReturnVO.setStatus(WebsocketTypeEnum.ZERO_ORDER.getValue());
						webSocketReturnVO.setMessage("您填写的方量是0m³，系统为您判断成为空跑订单。");
						String returnJson = JSONObject.toJSON(webSocketReturnVO).toString();
						webSocket.AppointSending(driverUser.getUsername(), returnJson);
					}


					//根据司机userid 查询司机姓名
					if(StringUtils.isNotBlank(driverUser.getName())){
						userName += driverUser.getName()+"、";
					}
					// 每次完成订单 +3 分
					HsmwScoringRecord hsmwScoringRecord = new HsmwScoringRecord();
					hsmwScoringRecord.setDriverId(driver.getId());
					hsmwScoringRecord.setInitialScore(driver.getScore());
					hsmwScoringRecord.setEndScore(String.valueOf(Integer.parseInt(driver.getScore()) + 3));
					hsmwScoringRecord.setFluctuateScore("3");
					hsmwScoringRecord.setRemark("完成订单");
					hsmwScoringRecords.add(hsmwScoringRecord);
					driver.setScore(String.valueOf(Integer.parseInt(driver.getScore()) + 3));

					List<HsmwDriverOrderRecord> list = hsmwDriverOrderRecordMapper.selectList(new LambdaQueryWrapper<HsmwDriverOrderRecord>().eq(HsmwDriverOrderRecord::getDriverId, driver.getId()));
					if(CollectionUtil.isEmpty(list)){
						// 首次完成订单 积分加50
						driver.setDriverIntegral(String.valueOf(Long.parseLong(driver.getDriverIntegral()) + 50));
						HsmwPointsDetails hsmwPointsDetails = new HsmwPointsDetails();
						hsmwPointsDetails.setDriverId(driver.getId());
						hsmwPointsDetails.setTypeIntegral(new BigDecimal(50));
						hsmwPointsDetails.setType("首次完成订单");
						hsmwPointsDetailsService.save(hsmwPointsDetails);
					}
					HsmwDriverOrderRecord record1 = new HsmwDriverOrderRecord();
					record1.setVehicleType(hsmwVehicle.getVehicleType());
					record1.setVehicleModel(hsmwVehicle.getVehicleModel());
					record1.setDriverId(driver.getId());
					record1.setOrderId(order.getId());
					record1.setVehicleNum(relation.getVehicleNum());
					record1.setVehicleId(relation.getVehicleId());
					record1.setOrderStatus(ChildOrderStatusEnum.COMPLETED.getValue());
					record1.setRealVolume(String.valueOf(driverVolume));
					record1.setSettlementVolume(settlementVolume);
					record1.setRelationId(relation.getId());
					record1.setEndTime(relation.getEndTime());
					record1.setItemId(order.getItemId());
					record1.setItemName(order.getItemName());
					record1.setItemPosition(order.getItemPosition());
					record1.setVehicleId(relation.getVehicleId());
					record1.setStartWorkTime(startWorkTime == null ? LocalDateTime.now() : startWorkTime);
					record1.setVehicleId(relation.getVehicleId());
					record1.setConstructionPosition(positionName.substring(0,positionName.length()-1));
					record1.setMovePumpCount(orderQueryParam.getMovePumpCount());
					record1.setLeasingCompanyId(driver.getOwnCompanyId());
					record1.setLeasingCompanyName(driver.getOwnCompanyName());
					record1.setChassisKilometers(orderQueryParam.getChassisKilometers());
					//2.2 添加的几个字段
					record1.setScore(driver.getScore());
					record1.setYears(hsmwVehicle.getYears());
					record1.setArmSegment(hsmwVehicle.getArmSegment());
					record1.setVehicleBrand(hsmwVehicle.getVehicleBrand());
					record1.setAxis(hsmwVehicle.getAxis());
					record1.setVehicleLeftImage(hsmwVehicle.getVehicleLeftImage());
					record1.setVehicleRightImage(hsmwVehicle.getVehicleRightImage());
					record1.setDriverUserId(driver.getUserId());
					record1.setChassisBrand(hsmwVehicle.getChassisBrand());
					record1.setTrafficRate(hsmwVehicle.getTrafficRate());
					records.add(record1);
					//司机完成订单 则 将 司机状态改为 休息中
					String id = driver.getId();
					HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, id).eq(HsmwBanDriver::getStatus, "0"));
					if(banDriver == null){
						driver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
					}else {
						driver.setWorkStatus(CommonConstants.BAN_WORK);
						HsmwScoringRecord scoringRecord = new HsmwScoringRecord();
						scoringRecord.setDriverId(driver.getId());
						scoringRecord.setInitialScore(driver.getScore());
						scoringRecord.setEndScore(String.valueOf(Long.parseLong(driver.getScore()) - Long.parseLong(banDriver.getDeductPoints())));
						scoringRecord.setFluctuateScore("-"+banDriver.getDeductPoints());
						scoringRecord.setRemark("封禁扣除评分");
						hsmwScoringRecordMapper.insert(scoringRecord);

						driver.setScore(String.valueOf(Long.parseLong(driver.getScore()) - Long.parseLong(banDriver.getDeductPoints())));
						banDriver.setStatus("1");
						hsmwBanDriverService.updateById(banDriver);
						HsmwReportRecord hsmwReportRecord = new HsmwReportRecord();
						if(StringUtils.isNotBlank(driver.getUserId())){
							HsmwDriverUser user = hsmwDriverUserService.getById(driver.getUserId());
							hsmwReportRecord.setDriverName(user.getName());
						}
						hsmwReportRecord.setDuration(banDriver.getDuration());
						hsmwReportRecord.setDeductPoints(banDriver.getDeductPoints());
						hsmwReportRecord.setReportId(banDriver.getComplainId());
						hsmwReportRecordService.save(hsmwReportRecord);
					}

				}
				hsmwOrderBalance.setDriverName(userName.substring(0,userName.length()-1));
				hsmwOrderBalance.setCarNum(hsmwVehicle.getCarNum());
				hsmwOrderBalance.setVehicleType(hsmwVehicle.getVehicleType());
				hsmwOrderBalance.setConstructionUnitName(order.getConstructionUnitName());
				hsmwOrderBalance.setConstructionPosition(positionName.substring(0,positionName.length()-1));
				hsmwOrderBalance.setItemId(order.getItemId());
				hsmwOrderBalance.setItemName(order.getItemName());
				hsmwOrderBalance.setRealVolume(String.valueOf(driverVolume));
				hsmwOrderBalance.setSettlementVolume(String.valueOf(settlementVolume));
				hsmwOrderBalance.setMovePumpCount(orderQueryParam.getMovePumpCount());
				hsmwOrderBalance.setFormulaTime(String.valueOf(formulaTime));
				hsmwOrderBalance.setStartWorkTime(realReachTime);
				hsmwOrderBalance.setEndTime(relation.getEndTime());
				hsmwOrderBalance.setWorkTime(String.valueOf(workTime+2));
				hsmwOrderBalance.setStatementsTime(LocalDateTime.now());
				hsmwOrderBalance.setOrderId(order.getId());
				HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(driverss.get(0).getOwnCompanyId());

				if(StringUtils.isNotNull(company)){
					hsmwOrderBalance.setRunSubsidy(company.getSubsidyAmount());
					hsmwOrderBalance.setMovePumpSubsidy(company.getMovePumpSubsidy());
				}

				String concreteNum = hsmwConcreteInfoMapper.findConcreteNumByPosionId(order.getId());
				if (concreteNum != null && StringUtils.isNotBlank(concreteNum)) {
					hsmwOrderBalance.setConcreteNum(concreteNum);
				}
				hsmwOrderBalance.setRelationId(relation.getId());
				hsmwOrderBalance.setVehicleId(relation.getVehicleId());
				hsmwOrderBalance.setDriverId(driverss.get(0).getId());
				hsmwOrderBalance.setConstructionTime(order.getCreateTime().toLocalDate());
				hsmwOrderBalance.setOrderStatus(relation.getOrderStatus());
				hsmwOrderBalance.setVehicleNum(relation.getVehicleNum());
				HsmwItem hsmwItem = hsmwItemService.getById(order.getItemId());
				if(StringUtils.isNotNull(hsmwItem) && StringUtils.isNotBlank(hsmwItem.getSettlementPrice())){
					if(StringUtils.equals("0",hsmwItem.getSettlementPrice())){
						hsmwOrderBalance.setMonovalent("0");
						hsmwOrderBalance.setMoney("0");
					}else {
						DecimalFormat df = new DecimalFormat("#.0");
						hsmwOrderBalance.setMonovalent(hsmwItem.getSettlementPrice());
						Double monovalent = Double.valueOf(hsmwOrderBalance.getMonovalent());
						String money = df.format(driverVolume * monovalent);
						if(StringUtils.equals(".0",money)){
							money = "0";
						}
						hsmwOrderBalance.setMoney(money);
					}
				}
				hsmwOrderBalance.setDifferenceVolume(String.valueOf(driverVolume));
				if(StringUtils.isNotBlank(hsmwOrderBalance.getWriteVolume()) && !StringUtils.equals("0",hsmwOrderBalance.getWriteVolume())){
					hsmwOrderBalance.setOutputVolume(hsmwOrderBalance.getWriteVolume());
				}else {
					hsmwOrderBalance.setOutputVolume(hsmwOrderBalance.getRealVolume());
				}

				//子订单状态为外租泵订单时候 冻结金额
				if(StringUtils.equals("1",relation.getOutsideLeasingFlag())){
					// 查找公司的泵送设置
					if(StringUtils.isNotBlank(hsmwVehicle.getVehicleModel()) && StringUtils.isNotBlank(hsmwVehicle.getLeasingCompanyId())) {
						HsmwReceiveOrderPrice hsmwReceiveOrderPrice = hsmwReceiveOrderPriceMapper.selectOne(new LambdaQueryWrapper<HsmwReceiveOrderPrice>().eq(HsmwReceiveOrderPrice::getVehicleModel, hsmwVehicle.getVehicleModel()).eq(HsmwReceiveOrderPrice::getSettleType, "1").eq(HsmwReceiveOrderPrice::getCompanyId, hsmwVehicle.getLeasingCompanyId()));
						HsmwSettlementRecord hsmwSettlementRecord = new HsmwSettlementRecord();
						BigDecimal settlePrice = null;
						if (StringUtils.isNotNull(hsmwReceiveOrderPrice) && hsmwReceiveOrderPrice.getSettlePrice() != null) {
							settlePrice = hsmwReceiveOrderPrice.getSettlePrice();
						} else {
							settlePrice = new BigDecimal(17);
						}
						// 计算冻结金额
						BigDecimal multiply = settlePrice.multiply(new BigDecimal(String.valueOf(driverVolume)));

						HsmwHtnUser htnUser = hsmwHtnUserService.getById(order.getCreateUser());

						if (StringUtils.isNotNull(htnUser) && StringUtils.isNotBlank(htnUser.getType())) {
							// 搅拌站永华
							if (StringUtils.equals(HtnUserTypeEnum.CONCRETE.getValue(), htnUser.getType())) {

								HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectById(htnUser.getOwnCompanyId());
								if (hsmwConcretePlantInfo != null) {
									if(hsmwConcretePlantInfo.getFrozenLimit() == null){
										hsmwConcretePlantInfo.setFrozenLimit(new BigDecimal(0));
									}
									hsmwConcretePlantInfo.setAvailableLimit(hsmwConcretePlantInfo.getAvailableLimit().subtract(multiply));
									hsmwConcretePlantInfo.setFrozenLimit(hsmwConcretePlantInfo.getFrozenLimit().add(multiply));
									hsmwConcretePlantInfoMapper.updateById(hsmwConcretePlantInfo);
									hsmwSettlementRecord.setAvailableLimit(hsmwConcretePlantInfo.getAvailableLimit());
									hsmwSettlementRecord.setOrderId(order.getId());
									hsmwSettlementRecord.setRelationId(relation.getId());
									hsmwSettlementRecord.setUserType(htnUser.getType());
									hsmwSettlementRecord.setSettlementType(SettlementStatusEnum.FROZEN.getValue());
									hsmwSettlementRecord.setFrozenLimit(multiply);
									hsmwSettlementRecord.setHandleUserId(loginUser.getId());
									hsmwSettlementRecord.setHandleUserName(loginUser.getName());
									hsmwSettlementRecord.setHandleTime(LocalDateTime.now());
									hsmwSettlementRecordMapper.insert(hsmwSettlementRecord);

								}

							}else if(StringUtils.equals(HtnUserTypeEnum.FOREMAN.getValue(), htnUser.getType())){
								// 如果当前用户 是工长用户  就根据订单的项目id 查询项目 再根据项目的创建人 去查询公司  扣除额度信息
								if(StringUtils.isNotBlank(order.getItemId())){
									HsmwItem item = hsmwItemService.getById(order.getItemId());
									if(StringUtils.isNotNull(item) && StringUtils.isNotBlank(item.getCreateUser())){
										HsmwHtnUser user = hsmwHtnUserService.getById(item.getCreateUser());
										if(user != null && StringUtils.isNotBlank(user.getOwnCompanyId()) && StringUtils.equals(HtnUserTypeEnum.COMPANY.getValue(), user.getType())){
											HsmwLeasingCompany leasingCompany = hsmwLeasingCompanyService.getById(user.getOwnCompanyId());
											if (leasingCompany != null) {
												if(leasingCompany.getFrozenLimit() == null){
													leasingCompany.setFrozenLimit(new BigDecimal(0));
												}
												leasingCompany.setFrozenLimit(leasingCompany.getFrozenLimit().add(multiply));
												leasingCompany.setAvailableLimit(leasingCompany.getAvailableLimit().subtract(multiply));
												hsmwLeasingCompanyService.updateById(leasingCompany);
												hsmwSettlementRecord.setAvailableLimit(leasingCompany.getAvailableLimit());
												hsmwSettlementRecord.setCompanyId(leasingCompany.getId());
												hsmwSettlementRecord.setOrderId(order.getId());
												hsmwSettlementRecord.setRelationId(relation.getId());
												hsmwSettlementRecord.setUserType(user.getType());
												hsmwSettlementRecord.setSettlementType(SettlementStatusEnum.FROZEN.getValue());
												hsmwSettlementRecord.setFrozenLimit(multiply);
												hsmwSettlementRecord.setHandleUserId(loginUser.getId());
												hsmwSettlementRecord.setHandleUserName(loginUser.getName());
												hsmwSettlementRecord.setHandleTime(LocalDateTime.now());
												hsmwSettlementRecordMapper.insert(hsmwSettlementRecord);
											}
										}else {
											HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectById(user.getOwnCompanyId());
											if (hsmwConcretePlantInfo != null) {
												if(hsmwConcretePlantInfo.getFrozenLimit() == null){
													hsmwConcretePlantInfo.setFrozenLimit(new BigDecimal(0));
												}
												hsmwConcretePlantInfo.setAvailableLimit(hsmwConcretePlantInfo.getAvailableLimit().subtract(multiply));
												hsmwConcretePlantInfo.setFrozenLimit(hsmwConcretePlantInfo.getFrozenLimit().add(multiply));
												hsmwConcretePlantInfoMapper.updateById(hsmwConcretePlantInfo);
												hsmwSettlementRecord.setAvailableLimit(hsmwConcretePlantInfo.getAvailableLimit());
												hsmwSettlementRecord.setOrderId(order.getId());
												hsmwSettlementRecord.setRelationId(relation.getId());
												hsmwSettlementRecord.setUserType(user.getType());
												hsmwSettlementRecord.setSettlementType(SettlementStatusEnum.FROZEN.getValue());
												hsmwSettlementRecord.setFrozenLimit(multiply);
												hsmwSettlementRecord.setHandleUserId(loginUser.getId());
												hsmwSettlementRecord.setHandleUserName(loginUser.getName());
												hsmwSettlementRecord.setHandleTime(LocalDateTime.now());
												hsmwSettlementRecordMapper.insert(hsmwSettlementRecord);
											}
										}
									}
								}
							}else if(StringUtils.equals(HtnUserTypeEnum.FOREMAN.getValue(), htnUser.getType())){
								// 如果当前用户 是工长用户  就根据订单的项目id 查询项目 再根据项目的创建人 去查询公司  扣除额度信息
								if(StringUtils.isNotBlank(order.getItemId())){
									HsmwItem item = hsmwItemService.getById(order.getItemId());
									if(StringUtils.isNotNull(item) && StringUtils.isNotBlank(item.getCreateUser())){
										HsmwHtnUser user = hsmwHtnUserService.getById(item.getCreateUser());
										if(user != null && StringUtils.isNotBlank(user.getOwnCompanyId()) && StringUtils.equals(HtnUserTypeEnum.COMPANY.getValue(), user.getType())){
											HsmwLeasingCompany leasingCompany = hsmwLeasingCompanyService.getById(user.getOwnCompanyId());
											if (leasingCompany != null) {
												if(leasingCompany.getFrozenLimit() == null){
													leasingCompany.setFrozenLimit(new BigDecimal(0));
												}
												leasingCompany.setFrozenLimit(leasingCompany.getFrozenLimit().add(multiply));
												leasingCompany.setAvailableLimit(leasingCompany.getAvailableLimit().subtract(multiply));
												hsmwLeasingCompanyService.updateById(leasingCompany);
												hsmwSettlementRecord.setAvailableLimit(leasingCompany.getAvailableLimit());
												hsmwSettlementRecord.setCompanyId(leasingCompany.getId());
												hsmwSettlementRecord.setOrderId(order.getId());
												hsmwSettlementRecord.setRelationId(relation.getId());
												hsmwSettlementRecord.setUserType(user.getType());
												hsmwSettlementRecord.setSettlementType(SettlementStatusEnum.FROZEN.getValue());
												hsmwSettlementRecord.setFrozenLimit(multiply);
												hsmwSettlementRecord.setHandleUserId(loginUser.getId());
												hsmwSettlementRecord.setHandleUserName(loginUser.getName());
												hsmwSettlementRecord.setHandleTime(LocalDateTime.now());
												hsmwSettlementRecordMapper.insert(hsmwSettlementRecord);
											}
										}else {
											HsmwConcretePlantInfo hsmwConcretePlantInfo = hsmwConcretePlantInfoMapper.selectById(user.getOwnCompanyId());
											if (hsmwConcretePlantInfo != null) {
												if(hsmwConcretePlantInfo.getFrozenLimit() == null){
													hsmwConcretePlantInfo.setFrozenLimit(new BigDecimal(0));
												}
												hsmwConcretePlantInfo.setAvailableLimit(hsmwConcretePlantInfo.getAvailableLimit().subtract(multiply));
												hsmwConcretePlantInfo.setFrozenLimit(hsmwConcretePlantInfo.getFrozenLimit().add(multiply));
												hsmwConcretePlantInfoMapper.updateById(hsmwConcretePlantInfo);
												hsmwSettlementRecord.setAvailableLimit(hsmwConcretePlantInfo.getAvailableLimit());
												hsmwSettlementRecord.setOrderId(order.getId());
												hsmwSettlementRecord.setRelationId(relation.getId());
												hsmwSettlementRecord.setUserType(user.getType());
												hsmwSettlementRecord.setSettlementType(SettlementStatusEnum.FROZEN.getValue());
												hsmwSettlementRecord.setFrozenLimit(multiply);
												hsmwSettlementRecord.setHandleUserId(loginUser.getId());
												hsmwSettlementRecord.setHandleUserName(loginUser.getName());
												hsmwSettlementRecord.setHandleTime(LocalDateTime.now());
												hsmwSettlementRecordMapper.insert(hsmwSettlementRecord);

											}
										}
									}
								}
							} else {
								//公司信息
								HsmwLeasingCompany leasingCompany = hsmwLeasingCompanyService.getById(htnUser.getOwnCompanyId());
								if (leasingCompany != null) {
									if(leasingCompany.getFrozenLimit() == null){
										leasingCompany.setFrozenLimit(new BigDecimal(0));
									}
									leasingCompany.setFrozenLimit(leasingCompany.getFrozenLimit().add(multiply));
									leasingCompany.setAvailableLimit(leasingCompany.getAvailableLimit().subtract(multiply));
									hsmwLeasingCompanyService.updateById(leasingCompany);
									hsmwSettlementRecord.setAvailableLimit(leasingCompany.getAvailableLimit());
									hsmwSettlementRecord.setCompanyId(leasingCompany.getId());
									hsmwSettlementRecord.setOrderId(order.getId());
									hsmwSettlementRecord.setRelationId(relation.getId());
									hsmwSettlementRecord.setUserType(htnUser.getType());
									hsmwSettlementRecord.setSettlementType(SettlementStatusEnum.FROZEN.getValue());
									hsmwSettlementRecord.setFrozenLimit(multiply);
									hsmwSettlementRecord.setHandleUserId(loginUser.getId());
									hsmwSettlementRecord.setHandleUserName(loginUser.getName());
									hsmwSettlementRecord.setHandleTime(LocalDateTime.now());
									hsmwSettlementRecordMapper.insert(hsmwSettlementRecord);
								}
							}
						}

						relation.setSettlementAmount(multiply);
						relation.setSettlementStatus(SettlementStatusEnum.FROZEN.getValue());
					}
				}
				hsmwScoringRecordService.saveBatch(hsmwScoringRecords);
				hsmwOrderBalanceMapper.insert(hsmwOrderBalance);
				hsmwDriverOrderRecordService.saveBatch(records);
				hsmwRunSprintRecordService.saveBatch(runSprintRecords);
				hsmwUserDriverService.saveOrUpdateBatch(driverss);

				List<HsmwPhoneBind> binds = hsmwPhoneBindService.list(new LambdaQueryWrapper<HsmwPhoneBind>()
						.eq(HsmwPhoneBind::getOrderId,order.getId()));
				if(CollectionUtil.isNotEmpty(binds)){
					binds.stream().forEach(hsmwPhoneBind -> {
						XuniTelNumVO telNumVOvo = new XuniTelNumVO();
						telNumVOvo.setPoolKey(CommonConstants.POOLKEY_1);
						telNumVOvo.setSecretNo(hsmwPhoneBind.getSecretNo());
						telNumVOvo.setSubsId(hsmwPhoneBind.getSubSid());
						IACasClientUtils.unBindAxb(telNumVOvo);
					});
				}
				//进行推送和存入系统消息
				String message = "泵车"+relation.getVehicleNum()+"已完成作业，请及时做出评价";
				String  foremanUserId = order.getCreateUser();
				String  foremanUsername = foremanUser.getUsername();
				//新增系统消息
				HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				hsmwDriverNews.setUserId(foremanUserId);
				hsmwDriverNews.setMessage(message);
				hsmwDriverNews.setAlreadyRead("0");
				hsmwDriverNewsService.save(hsmwDriverNews);
				WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
				webSocketReturnVO.setRelationId(relation.getId());
				TencentPushUtils.selfrunCanCelMsg(message,foremanUsername,"has_new_message",webSocketReturnVO);
				//解绑后 删除该订单的相关的隐私号码信息
				hsmwPhoneBindService.remove(new LambdaQueryWrapper<HsmwPhoneBind>().
						eq(HsmwPhoneBind::getOrderId,order.getId()));
			}

			WeapPushUtils.pushForemanMsg(vo,hsmwGpsService);
			// 修改主订单信息
			order.setOrderStatus(OrderStatusEnum.COMPLETED.getValue());
			hsmwOrderService.updateById(order);
			// 修改子订单信息
			hsmwOrderVehicleRelationService.updateById(relation);
			WeapPushUtils.pushForemanMsg(vo,hsmwGpsService);
			return new DataResponse();
		} catch (Exception e) {
			e.printStackTrace();
			return new DataResponse(FAIL, "更新订单的状态失败，请联系系统管理员！");
		}
	}




	public List<TaskingOrderVO> getDriversByOrderId(HashMap param) {
		return  hsmwUserDriverMapper.getDriversByOrderId(param);
	}

    public DriveTotalInfoVO getDriverTotalInfo(HashMap param) {
		return  hsmwUserDriverMapper.getDriverTotalInfo(param);
    }
	public DriveTotalInfoVO getAndroDriverTotalInfo(HashMap param) {
		return  hsmwUserDriverMapper.getAndroDriverTotalInfo(param);
	}


	public void saveOrUpdateDriverStatus(HsmwUserDriver hsmwUserDriver) {
		//当休息中变为接单中的时候 查询一下也没有待推送的订单信息
		HashMap param = new HashMap();
		param.put("userId",hsmwUserDriver.getUserId());
		if(CommonConstants.DRIVER_ACCEPT_ORDER.equals(hsmwUserDriver.getWorkStatus())) {
			// 根据车辆id 查询一下有没有进行中的订单 如果车辆有订单 则 把司机的状态更改为工作中
			HashMap params = new HashMap();
			params.put("vehicleId",hsmwUserDriver.getVehicleId());
			if(params.get("vehicleId") != null){
				List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(params);
				if(CollectionUtil.isNotEmpty(orderList)){
					hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
				}
			}
		}
		if(CommonConstants.DRIVER_FREE.equals(hsmwUserDriver.getWorkStatus())){
			String key = "driver:status:"+hsmwUserDriver.getId();
			redisTemplate.opsForValue().set(key,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		}

		hsmwUserDriverMapper.updateById(hsmwUserDriver);
	}


	public List<OrderPoolVO> transferJSONToBean(List<JSONObject> result){
		List<OrderPoolVO> res = new ArrayList<>();
		if(CollectionUtil.isNotEmpty(result)){
			for(JSONObject object:result){
				OrderPoolVO u = JSON.parseObject(object.toJSONString(), OrderPoolVO.class);
				res.add(u);
			}
		}
		return res;
	}

	public boolean checkIfHasGoing(String orderId){
		List<HsmwOrderVehicleRelation> rea = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>()
				.eq(HsmwOrderVehicleRelation::getOrderId,orderId).
						eq(HsmwOrderVehicleRelation::getOrderStatus,ChildOrderStatusEnum.ARRIVED.getValue()));
		if(CollectionUtil.isNotEmpty(rea)){
			return true;
		}else {
			return false;
		}
	}

    public void resetVehicleBindDrivers(HashMap param) {
		hsmwUserDriverMapper.resetVehicleBindDrivers(param);

    }

	public List<com.hsmw.domain.vo.DriverCountVO> findUserDriverListBYVehicleId(String vehicleId) {

		return hsmwUserDriverMapper.findUserDriverListBYVehicleId(vehicleId);
	}

	/**
	 * 抢单接口
	 *
	 * @param
	 * @return
	 *//*
	public synchronized DataResponse grabbingOrders(OrderQueryParam orderQueryParam) throws Exception {
		WebSocketReturnVO grabbStatus  = new WebSocketReturnVO();
		//新的抢单逻辑 begin ======
		LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
		System.out.println("抢单时间 ==== "+new Date());
		HsmwOrder orderInfo = hsmwOrderService.getById(orderQueryParam.getOrderId());
		HashMap queryparam = new HashMap();
		queryparam.put("userId",hsmwUser.getId());
		HsmwUserDriver driver = hsmwUserDriverMapper.selectDriverInfoByUserId(queryparam);
		HsmwVehicle vehicle = hsmwVehicleService.getVehicleById(driver.getVehicleId());
		//订单的项目信息
		HsmwItem itemInfo = hsmwItemService.getHsmwItemById(orderInfo.getItemId());
		OrderPoolVO vo = new OrderPoolVO();
		if(StringUtils.isNotBlank(itemInfo.getVehicleUnitId()) && itemInfo.getVehicleUnitId().equals(vehicle.getLeasingCompanyId())){
			//如果车辆属于 项目的指定公司 那么 OrderPoolVO 的是否是指定车辆的抢单。
			vo.setAppointCompanyOrder(true);
		}else{
			vo.setAppointCompanyOrder(false);
		}
		HsmwOrderVehicleRequest hsmwOrderVehicleRequest = hsmwOrderVehicleRequestService.getById(orderQueryParam.getRequestId());
		List<JSONObject> result = redisCache.getCacheList(orderQueryParam.getRequestId());
		List<OrderPoolVO> poolVOListlist = new ArrayList<>();
		if(CollectionUtil.isNotEmpty(result)){
			poolVOListlist=JSONUtils.transferJSONToBean(result);
		}
		//如果该 需求（池子）里面并没有人在里面 或者是 这个抢单的人不在里面 那么 将该用户添加进池子
		if(CollectionUtil.isEmpty(poolVOListlist) ){
			poolVOListlist =new ArrayList<>();
			vo.setForemanLinkTel(orderInfo.getCreateUserTel());
			vo.setVehicleId(driver.getVehicleId());
			vo.setBeginTime(LocalDateTime.now());
			vo.setOrderId(orderQueryParam.getOrderId());
			vo.setDriverId(driver.getId());
			vo.setUserId(hsmwUser.getId());
			vo.setRequestId(orderQueryParam.getRequestId());
			vo.setScore(driver.getScore());
			vo.setDriverName(hsmwUser.getName());
			vo.setDriverUsername(hsmwUser.getUsername());
			vo.setVehicleNum(vehicle.getVehiclePlate());
			vo.setVehicleModel(vehicle.getVehicleModel());
			vo.setVehicleType(vehicle.getVehicleType());
			vo.setLeasingCompanyId(vehicle.getLeasingCompanyId());
			vo.setLeasingCompanyName(vehicle.getLeasingCompanyName());
			vo.setExpectVolume(orderInfo.getExpectVolume());
			vo.setLeasingCompanyType(vehicle.getLeasingCompanyType());
			vo.setReachTime(orderInfo.getReachTime());
			vo.setImeiNum(vehicle.getImeiNum());
			vo.setLng(orderInfo.getLng());
			vo.setLat(orderInfo.getLat());
			poolVOListlist.add(vo);
			redisCache.setCacheList(orderQueryParam.getRequestId(),poolVOListlist);
			grabbStatus.setStatus(WebsocketTypeEnum.GRABBING.getValue());
			grabbStatus.setMessage("抢单开始，倒计时开始");
			grabbStatus.setRemaindSeconds(15);
			// // 定时器实例
			Timer timerBean = getTimerEntity();
			//15s 后进行订单分发 的定时器
			OrderTimeTask task =  new OrderTimeTask( redisCache,hsmwOrderDistributeInfoService,orderInfo,webSocket,hsmwOrderVehicleRelationService,hsmwOrderVehicleRequest,hsmwUserDriverService,hsmwUserMapper,hsmwOrderService,hsmwVehicleService,hsmwOrderVehicleRequestService,vo,orderPool,hsmwPhoneBindService);
			Date startTime = new Date(new Date().getTime()+8*1000);
			timerBean.schedule(task,startTime);
			return DataResponse.success(grabbStatus);
		}
		//如果已经有人在抢，那么将这个人添加进抢单的队列返回剩余的秒数。
		else if (StringUtils.isListNotNull(poolVOListlist) && !checkIfExists(poolVOListlist,hsmwUser.getId())){
			System.out.println("添加之前的list poolVOListlist=="+poolVOListlist.size());
			//如果已经有人在抢，并且 与他同车的司机也在池子里面， 那么这个人抢单失败
			//查询出来与他同车的司机
			LambdaQueryWrapper<HsmwUserDriver> lambdaQueryWrapper  = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(HsmwUserDriver::getVehicleId,driver.getVehicleId());
			lambdaQueryWrapper.ne(HsmwUserDriver::getId,driver.getId());
			List<HsmwUserDriver> hsmwUserDriverList = hsmwUserDriverMapper.selectList(lambdaQueryWrapper);
			for(HsmwUserDriver drivers:hsmwUserDriverList){
				if(checkIfExists(poolVOListlist,drivers.getUserId())){
					grabbStatus.setStatus(WebsocketTypeEnum.MATEDRIVER.getValue());
					grabbStatus.setMessage("您的同车辆人员已参与抢单！");
					grabbStatus.setRemaindSeconds(0);
					return DataResponse.success(grabbStatus);
				}
			}
			vo.setBeginTime(LocalDateTime.now());
			vo.setOrderId(orderQueryParam.getOrderId());
			vo.setDriverId(driver.getId());
			vo.setUserId(hsmwUser.getId());
			vo.setScore(driver.getScore());
			vo.setRequestId(orderQueryParam.getRequestId());
			vo.setVehicleId(driver.getVehicleId());
			vo.setDriverName(hsmwUser.getName());
			vo.setDriverUsername(hsmwUser.getUsername());
			vo.setVehicleNum(vehicle.getVehiclePlate());
			vo.setVehicleModel(vehicle.getVehicleModel());
			vo.setVehicleType(vehicle.getVehicleType());
			vo.setLeasingCompanyId(vehicle.getLeasingCompanyId());
			vo.setLeasingCompanyName(vehicle.getLeasingCompanyName());
			vo.setExpectVolume(orderInfo.getExpectVolume());
			vo.setLeasingCompanyType(vehicle.getLeasingCompanyType());
			vo.setReachTime(orderInfo.getReachTime());
			vo.setImeiNum(vehicle.getImeiNum());
			vo.setLng(orderInfo.getLng());
			vo.setLat(orderInfo.getLat());
			poolVOListlist.add(vo);
			//
			redisCache.deleteObject(orderQueryParam.getRequestId());
			redisCache.setCacheList(orderQueryParam.getRequestId(),poolVOListlist);
			System.out.println("添加之前后list poolVOListlist=="+poolVOListlist.size());

			//orderPool.put(orderQueryParam.getRequestId(),poolVOListlist);
			grabbStatus.setStatus(WebsocketTypeEnum.GRABBING.getValue());
			grabbStatus.setMessage("抢单开始，倒计时开始");
			OrderPoolVO first = poolVOListlist.get(0);
			long seconds =(first.getBeginTime().getSecond()-vo.getBeginTime().getSecond());
			grabbStatus.setRemaindSeconds(seconds);
			return DataResponse.success(grabbStatus);
		}
		//每抢单完一次以后 将最新的 抢单池放进redis
		//redisCache.setCacheObject("orderPool",orderPool);
		return DataResponse.success(grabbStatus);
	}
*/


	public List<PeerDriverVO> orderPeerDrivers(HashMap param) {
		return hsmwUserDriverMapper.orderPeerDrivers(param);
	}

	public List<DriverInfo> findDriverListByVehicleId(String id) {
		List<DriverInfo> list = new ArrayList<>();
		List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, id));
		HsmwVehicle vehicle = hsmwVehicleService.getById(id);
		if(CollectionUtil.isNotEmpty(hsmwUserDrivers)){
			for (HsmwUserDriver hsmwUserDriver : hsmwUserDrivers) {
				String userId = hsmwUserDriver.getUserId();
				HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(userId);
				if(StringUtils.isNotNull(hsmwUser)){
					DriverInfo driverInfo = new DriverInfo();
					driverInfo.setDriverUsername(hsmwUser.getUsername());
					driverInfo.setName(hsmwUser.getName());
					driverInfo.setImages(hsmwUserDriver.getMyPicture());
					driverInfo.setVehicleNum(hsmwUserDriver.getId());
					driverInfo.setStatus(hsmwUserDriver.getWorkStatus());
					driverInfo.setVehicleId(hsmwUserDriver.getVehicleId());
					driverInfo.setMaxDriverNumber(vehicle.getMaxDriverNumber());
					list.add(driverInfo);
				}
			}
		}
		return list;
	}

    public void updateVehicleIdAndWorkStatus(String id, String changingCars) {
		hsmwUserMapper.updateVehicleIdAndWorkStatus(id,changingCars);
	}

	public List<DriverDetailVO> findDriverListById(String vehicleId) {
		return hsmwUserDriverMapper.findDriverListById(vehicleId);
	}

	public List<RelationOrderVo> findRelationOrderListByDriId(String key,String month) {

		return hsmwUserDriverMapper.findRelationOrderListByDriId(key,month);
	}

	public List<HomeVolume> findItemPerOnWeek(String id) {
		return hsmwUserDriverMapper.findItemPerOnWeek(id);
	}

	public List<HomeVolume> findItemPerOnMonth(String id,String month) {
		return hsmwUserDriverMapper.findItemPerOnMonth(id,month);
	}

	public List<HsmwUserDriver> selectAvaliableList(String vehicleId){
		List<HsmwUserDriver> drivers=  hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>()
				.eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_ACCEPT_ORDER)
				.eq(HsmwUserDriver::getVehicleId,vehicleId));
		if(CollectionUtil.isNotEmpty(drivers)){
			Iterator<HsmwUserDriver> iterator = drivers.iterator();
			while (iterator.hasNext()) {
				HsmwUserDriver hsmwUserDriver = iterator.next();
				HashMap param = new HashMap();
				param.put("driverId",hsmwUserDriver.getId());
				if (hsmwReportService.checkDriverHasleavingRecord(param)) {
					iterator.remove();
				}
			}
		}
		return drivers;
	}

	public List<HsmwUserDriver> selectAppointAvaliableList(String vehicleId){
		List<HsmwUserDriver> drivers=  hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>()
				.in(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_ACCEPT_ORDER,CommonConstants.DRIVER_FREE)
				.eq(HsmwUserDriver::getVehicleId,vehicleId));
		if(CollectionUtil.isNotEmpty(drivers)){
			Iterator<HsmwUserDriver> iterator = drivers.iterator();
			while (iterator.hasNext()) {
				HsmwUserDriver hsmwUserDriver = iterator.next();
				HashMap param = new HashMap();
				param.put("driverId",hsmwUserDriver.getId());
				if (hsmwReportService.checkDriverHasleavingRecord(param)) {
					iterator.remove();
				}
			}
		}
		return drivers;
	}


	public List<HomeVolume> findVehicleVolumeByMonth(String id, String month) {
		return hsmwUserDriverMapper.findVehicleVolumeByMonth(id,month);
	}

	public List<DriverDetailVO> findDriverListByRelatId(String id) {

		return hsmwUserDriverMapper.findDriverListByRelatId(id);
	}


	public static void main(String[] args) {


		System.err.println(Double.valueOf(112));

		System.err.println(Double.parseDouble("14.59"));

	}


	/**
	 * 修改预计到达时间
	 * @param hsmwPushInfo
	 * @return
	 */
	public DataResponse updateDriverReachTime(HsmwPushInfo hsmwPushInfo) {
		if (StringUtils.isNull(hsmwPushInfo)) {
			return new DataResponse(VALIDATE_FAILED, "传递参数不可为空");
		}
		HsmwPushInfo one = hsmwPushInfoService.getOne(new LambdaQueryWrapper<HsmwPushInfo>().eq(HsmwPushInfo::getOrderId, hsmwPushInfo.getOrderId()).eq(HsmwPushInfo::getDriverId,hsmwPushInfo.getDriverId()));
		if(StringUtils.isNotNull(one)){
			return new DataResponse(FAIL,"您已申请，请勿重复提交");
		}
		hsmwPushInfo.setType("UPDATE_TIME");
		// 保存信息
		boolean save = hsmwPushInfoService.save(hsmwPushInfo);
		boolean suc = true;
		// 保存提交记录之后 向工长端发送通知
		if (StringUtils.isNotBlank(hsmwPushInfo.getOrderId())) {
			// 根据订单id 查询订单的创建人信息 向创建人发送通知消息
			HsmwOrder order = hsmwOrderService.getById(hsmwPushInfo.getOrderId());
			if (StringUtils.isNotNull(order) && StringUtils.isNotBlank(order.getCreateUser())) {
				HsmwHtnUser user = hsmwHtnUserService.getById(order.getCreateUser());
				if (StringUtils.isNotNull(user)) {
					HsmwUserDriver userDriver = hsmwUserDriverService.getById(hsmwPushInfo.getDriverId());
					if (StringUtils.isNotNull(userDriver)) {
						HsmwVehicle vehicle = hsmwVehicleService.getById(userDriver.getVehicleId());
						if (StringUtils.isNotNull(vehicle)) {
							String message = vehicle.getVehiclePlate();
							String msgs = "泵车" + message + "的司机申请修改订单预计到达时间，请前往APP进行查看";
							// 企业版
							if (StringUtils.equals(HtnUserTypeEnum.COMPANY.getValue(), user.getType()) || StringUtils.equals(UserTypeEnum.PLATFORM.getValue(), user.getType())) {
								WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
								webSocketReturnVO.setPushId(hsmwPushInfo.getId());
								webSocketReturnVO.setMessage(hsmwPushInfo.getMessage());
								webSocketReturnVO.setOrderId(hsmwPushInfo.getOrderId());
								webSocketReturnVO.setReachTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(hsmwPushInfo.getDriverReachTime()));
								webSocketReturnVO.setRelationId(hsmwPushInfo.getRelationId());
								webSocketReturnVO.setStatus(order.getIfConcreteRequired());
								TencentPushUtils.selfrunCanCelMsg(msgs, user.getUsername(), "has_new_message", webSocketReturnVO);
								SendSmsUtil.sendBizOrderSmsCode(appId, appKey, message, updateDriverReachTime, smsSign, user.getUsername());
								HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
								hsmwDriverNews.setUserId(user.getId());
								hsmwDriverNews.setMessage(msgs);
								hsmwDriverNews.setAlreadyRead("0");
								suc = hsmwDriverNewsService.save(hsmwDriverNews);
							} else {// 项目版
								WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
								webSocketReturnVO.setPushId(hsmwPushInfo.getId());
								webSocketReturnVO.setMessage(hsmwPushInfo.getMessage());
								webSocketReturnVO.setOrderId(hsmwPushInfo.getOrderId());
								webSocketReturnVO.setRelationId(hsmwPushInfo.getRelationId());
								webSocketReturnVO.setStatus(order.getIfConcreteRequired());
								webSocketReturnVO.setReachTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(hsmwPushInfo.getDriverReachTime()));
								TencentPushUtils.pushCancelForeManMsg(msgs, user.getUsername(), "has_new_message", webSocketReturnVO);
								SendSmsUtil.sendBizOrderSmsCode(appId, appKey, message, updateDriverReachTime, smsSign, user.getUsername());
								HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
								hsmwDriverNews.setUserId(user.getId());
								hsmwDriverNews.setMessage(msgs);
								hsmwDriverNews.setAlreadyRead("0");
								suc = hsmwDriverNewsService.save(hsmwDriverNews);
							}
						}
					}
				}
			}
		}
		if(suc && save){
			return new DataResponse(SUCCESS);
		}else {
			return new DataResponse(FAIL);
		}
	}

	/**
	 * 同意或者不同意司机申请的预计到达时间修改
	 * @param hsmwPushInfo
	 * @return
	 */
	public DataResponse agreeDriverUpdateReachTime(HsmwPushInfo hsmwPushInfo) {

		if(StringUtils.isNull(hsmwPushInfo)){
			return new DataResponse(FAIL,"传递参数不能为空");
		}
		if(StringUtils.equals("1",hsmwPushInfo.getStatus())){
			//同意修改预计到达时间
			hsmwPushInfo.setStatus("1");
			LocalDateTime driverReachTime = hsmwPushInfo.getDriverReachTime();
			//获取子订单id
			String orderId = hsmwPushInfo.getRelationId();
			HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(orderId);
			if(StringUtils.isNotNull(relation) && StringUtils.isNotBlank(relation.getOrderVehicleRequestId())){
				HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(relation.getOrderVehicleRequestId());
				if(StringUtils.isNotNull(request)){
					request.setReachTime(hsmwPushInfo.getDriverReachTime());
					hsmwOrderVehicleRequestService.updateById(request);
				}
			}
			String msg = "对方同意了您的申请，订单预计到达时间修改成功！";
			HsmwPushInfo info = hsmwPushInfoService.getById(hsmwPushInfo.getId());
			if(StringUtils.isNotNull(info)){
				HsmwUserDriver userDriver = hsmwUserDriverService.getById(info.getDriverId());
				if(StringUtils.isNotNull(userDriver)){
					HsmwDriverUser user = hsmwDriverUserService.getById(userDriver.getUserId());
					TencentPushUtils.pushMsg(msg,user.getUsername(),"has_new_message");
					HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
					hsmwDriverNews.setUserId(user.getId());
					hsmwDriverNews.setMessage(msg);
					hsmwDriverNews.setAlreadyRead("0");
					hsmwDriverNewsService.save(hsmwDriverNews);
				}
			}
		}else {
			//不同意修改预计到达时间
			hsmwPushInfo.setStatus("2");
			String msg = "对方拒绝了您的申请，订单预计到达时间修改失败！";
			HsmwPushInfo info = hsmwPushInfoService.getById(hsmwPushInfo.getId());
			if(StringUtils.isNotNull(info)){
				HsmwUserDriver userDriver = hsmwUserDriverService.getById(info.getDriverId());
				if(StringUtils.isNotNull(userDriver)){
					HsmwDriverUser user = hsmwDriverUserService.getById(userDriver.getUserId());
					TencentPushUtils.pushMsg(msg,user.getUsername(),"has_new_message");
					HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
					hsmwDriverNews.setUserId(user.getId());
					hsmwDriverNews.setMessage(msg);
					hsmwDriverNews.setAlreadyRead("0");
					hsmwDriverNewsService.save(hsmwDriverNews);
				}
			}
		}
		boolean suc = hsmwPushInfoService.updateById(hsmwPushInfo);
		if(suc){
			return new DataResponse(SUCCESS);
		}else {
			return new DataResponse(FAIL);
		}
	}

	public DataResponse findDriverPushInfoByOrderId(String relationId) {
		List<HsmwPushInfo> list = hsmwPushInfoService.list(new LambdaQueryWrapper<HsmwPushInfo>()
				.eq(HsmwPushInfo::getRelationId, relationId).eq(HsmwPushInfo::getStatus, "0")
				.eq(HsmwPushInfo::getType,PushTypeEnum.UPDATE_TIME.getValue()));
		List<WebSocketReturnVO> vos = new ArrayList<>();
		if(CollectionUtil.isNotEmpty(list)){
			list.stream().forEach(hsmwPushInfo -> {
				WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
				webSocketReturnVO.setPushId(hsmwPushInfo.getId());
				webSocketReturnVO.setOrderId(hsmwPushInfo.getOrderId());
				webSocketReturnVO.setReachTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(hsmwPushInfo.getDriverReachTime()));
				webSocketReturnVO.setRelationId(hsmwPushInfo.getRelationId());
				webSocketReturnVO.setMessage(hsmwPushInfo.getMessage());
				vos.add(webSocketReturnVO);
			});

		}
		return new DataResponse(vos);
	}

	public DataResponse findDriverReachTimeInfoByOrderId(String orderId,String driverId) {

		if(StringUtils.isBlank(orderId)){
			return new DataResponse(FAIL,"传递参数不可为空");
		}
		HsmwPushInfo one = hsmwPushInfoService.getOne(new LambdaQueryWrapper<HsmwPushInfo>().eq(HsmwPushInfo::getRelationId, orderId).eq(HsmwPushInfo::getDriverId,driverId).eq(HsmwPushInfo::getType,PushTypeEnum.UPDATE_TIME));
		return new DataResponse(one);
	}

	public DataResponse findDriverReportPushInfoByOrderId(String relationId) {
		List<HsmwPushInfo> ones = hsmwPushInfoService.list(new LambdaQueryWrapper<HsmwPushInfo>()
				.eq(HsmwPushInfo::getRelationId, relationId)
				.eq(HsmwPushInfo::getStatus, "0")
				.eq(HsmwPushInfo::getType,PushTypeEnum.DRIVER_REPORT.getValue()));
		List<WebSocketReturnVO> list = new ArrayList<>();
		if(CollectionUtil.isNotEmpty(ones)){
			for (HsmwPushInfo one : ones) {
				WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
				webSocketReturnVO.setPushId(one.getId());
				webSocketReturnVO.setOrderId(one.getOrderId());
				webSocketReturnVO.setRelationId(one.getRelationId());
				webSocketReturnVO.setMessage(one.getMessage());
				webSocketReturnVO.setReportId(one.getReportId());
				list.add(webSocketReturnVO);
			}
		}
		return new DataResponse(list);
	}

	/**
	 * 工长是否取消订单
	 * @param hsmwPushInfo
	 * @return
	 */
	public DataResponse updateReportAndOrderInfo(HsmwPushInfo hsmwPushInfo) {
		LoginUser loginUser =  currentHsmwUserUtils.getCurrentUserInfo();
		//保持订单
		if(StringUtils.equals("1",hsmwPushInfo.getType())){
			HsmwReport report = hsmwReportService.getById(hsmwPushInfo.getReportId());
			report.setCommunicate(hsmwPushInfo.getDataInfo());
			hsmwReportService.updateById(report);
		}else {
			HsmwReport report = hsmwReportService.getById(hsmwPushInfo.getReportId());
			report.setCommunicate(hsmwPushInfo.getDataInfo());
			hsmwReportService.updateById(report);
			HsmwOrder order = hsmwOrderService.getById(hsmwPushInfo.getOrderId());
			if(StringUtils.isNotNull(order)){
				if(StringUtils.equals("0",order.getIfConcreteRequired())){
					//泵车订单 取消request releation order
					order.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
					order.setEndTime(LocalDateTime.now());
					order.setRemark("工长取消订单！");
					hsmwOrderService.updateById(order);
					HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(hsmwPushInfo.getRelationId());
					if(null != relation){
						relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
						relation.setEndTime(LocalDateTime.now());
					}
					HsmwOrderVehicleRequest hsmwOrderVehicleRequest =  new HsmwOrderVehicleRequest();
					hsmwOrderVehicleRequest.setId(relation.getOrderVehicleRequestId());
					hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
					//
					hsmwOrderVehicleRequest.setOperUserId(loginUser.getId());
					hsmwOrderVehicleRequest.setOperType(CancleTypeEnum.FOREMAN_CANCLE.getValue());
					hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());

					hsmwOrderVehicleRequestService.updateById(hsmwOrderVehicleRequest);
					hsmwOrderVehicleRelationService.updateById(relation);
					//查询司机的
					List<HsmwUserDriver> driverss = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
							.eq(HsmwUserDriver::getVehicleId, relation.getVehicleId()).eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
					HsmwVehicle vehicle = hsmwVehicleService.getById(relation.getVehicleId());
					//存储一下
					List<HsmwDriverCancelOrderRecord> records = new ArrayList<>();
					if(CollectionUtil.isNotEmpty(driverss)){
						for (HsmwUserDriver hsmwUserDriver : driverss) {
							HsmwDriverCancelOrderRecord record = new HsmwDriverCancelOrderRecord();
							HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(hsmwUserDriver.getUserId());
							if (hsmwDriverUser != null && StringUtils.isNotBlank(hsmwDriverUser.getName()) && StringUtils.isNotBlank(hsmwDriverUser.getUsername())) {
								record.setDriverUsername(hsmwDriverUser.getUsername());
								record.setDriverName(hsmwDriverUser.getName());
							}
							record.setDriverId(hsmwUserDriver.getId());
							record.setOrderId(relation.getOrderId());
							record.setVehicleNum(relation.getVehicleNum());
							record.setVehicleId(relation.getVehicleId());
							record.setRequestId(relation.getOrderVehicleRequestId());
							record.setOrderStatus(ChildOrderStatusEnum.COMPLETED.getValue());
							record.setRelationId(relation.getId());
							record.setItemName(order.getItemName());
							record.setItemPosition(order.getItemPosition());
							record.setVehicleId(relation.getVehicleId());
							record.setVehicleId(vehicle.getId());
							record.setConstructionPosition(order.getConstructionPosition());
							//2.2 添加的几个字段
							record.setScore(hsmwUserDriver.getScore());
							record.setDriverUserId(hsmwUserDriver.getUserId());
							record.setYears(vehicle.getYears());
							record.setArmSegment(vehicle.getArmSegment());
							record.setVehicleBrand(vehicle.getVehicleBrand());
							record.setAxis(vehicle.getAxis());
							record.setVehicleLeftImage(vehicle.getVehicleLeftImage());
							record.setVehicleRightImage(vehicle.getVehicleRightImage());
							record.setDriverUserId(hsmwUserDriver.getUserId());
							record.setChassisBrand(vehicle.getChassisBrand());
							record.setTrafficRate(vehicle.getTrafficRate());
							records.add(record);

							hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
						}
					}
					if(CollectionUtil.isNotEmpty(records)){
						hsmwDriverCancelOrderRecordService.saveBatch(records);
					}
					if (CollectionUtil.isNotEmpty(driverss)){
						hsmwUserDriverService.updateBatchById(driverss);
					}
					vehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
					hsmwVehicleService.updateById(vehicle);
				}else {
					// 混凝土订单 取消request releation
					HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(hsmwPushInfo.getRelationId());
					if(StringUtils.isNotNull(relation)){
						relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
						hsmwOrderVehicleRelationService.updateById(relation);
						HsmwOrderVehicleRequest hsmwOrderVehicleRequest =  new HsmwOrderVehicleRequest();
						hsmwOrderVehicleRequest.setId(relation.getOrderVehicleRequestId());
						hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
						//搅拌站取消的话 将 取消类型设置为 1
						hsmwOrderVehicleRequest.setOperType(CancleTypeEnum.FOREMAN_CANCLE.getValue());
						hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
						hsmwOrderVehicleRequest.setEndTime(LocalDateTime.now());
						hsmwOrderVehicleRequestService.updateById(hsmwOrderVehicleRequest);
						List<HsmwUserDriver> driverss = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
								.eq(HsmwUserDriver::getVehicleId, relation.getVehicleId()).eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
						for (HsmwUserDriver userDriver : driverss) {
							userDriver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
						}
						hsmwUserDriverService.updateBatchById(driverss);
						HsmwVehicle vehicle = hsmwVehicleService.getById(relation.getVehicleId());
						vehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
						hsmwVehicleService.updateById(vehicle);
					}
				}
			}
		}
		hsmwPushInfo.setStatus("1");
		boolean suc = hsmwPushInfoService.updateById(hsmwPushInfo);
		if(suc){
			return new DataResponse(SUCCESS);
		}else {
			return new DataResponse(FAIL);
		}
	}

	/**
	 * 司机查看自己的换车申请
	 * @param id
	 * @return
	 */
	public DataResponse findExchangeBusBydriverId(String id) {
		DriverInfo driverInfo = new DriverInfo();
		HsmwExchangeBus one = hsmwExchangeBusService.getOne(new LambdaQueryWrapper<HsmwExchangeBus>().eq(HsmwExchangeBus::getDriverId, id).eq(HsmwExchangeBus::getApplyStatus, "0"));
		if(StringUtils.isNotNull(one) && StringUtils.isNotBlank(one.getExchangeDriverId())){
			HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(one.getExchangeDriverId());
			if(StringUtils.isNotNull(userDriver)){
				HsmwDriverUser user = hsmwDriverUserMapper.selectById(userDriver.getUserId());
				HsmwVehicle vehicle = hsmwVehicleService.getById(userDriver.getVehicleId());
				if(StringUtils.isNotNull(vehicle)){
					driverInfo.setVehicleNum(vehicle.getVehiclePlate());
				}
				driverInfo.setName(user.getName());
				driverInfo.setDriverUsername(user.getUsername());
				driverInfo.setImages(userDriver.getMyPicture());
				driverInfo.setExchangeId(one.getId());
			}
			return new DataResponse(driverInfo);
		}else {
			return new DataResponse(null);
		}
	}

	public DataResponse driverSeeLineChart(DriverLineChart driverLineChart) throws ParseException {

		Map map = new HashMap();
		String id = driverLineChart.getId();
		if (StringUtils.isBlank(id)) {
			return new DataResponse(FAIL, "id不可为空");
		}

		HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(driverLineChart.getId());
		/*if (StringUtils.isNull(userDriver) || StringUtils.isBlank(userDriver.getVehicleId())) {
			return new DataResponse(FAIL, "该司机没有车辆信息");
		}*/
		List<cn.hutool.json.JSONObject> reachVolume = Lists.newArrayList();
		String sumVolume = hsmwDriverOrderRecordMapper.findDriverOrderListRealVolumeById(driverLineChart);
		map.put("sumVolume", sumVolume);

		List<VehicleInfoByTypeDTO> vehicleInfoByTypeDTOS = hsmwDriverOrderRecordMapper.findDriverOrderListVehicleById(driverLineChart);
		map.put("vehicleInfo", vehicleInfoByTypeDTOS);

		String workTime= hsmwDriverOrderRecordMapper.findDriverWorkTimeById(driverLineChart);
		map.put("workTime",workTime);

		List<ItemFroDriverDTO> itemFroDriverDTOS = hsmwDriverOrderRecordMapper.findDriverOrderOnItemInfoById(driverLineChart);
		map.put("itemInfo",itemFroDriverDTOS);

		Integer completeCount = hsmwDriverOrderRecordMapper.findDriverOrderOncompleteCount(driverLineChart);
		Integer cancelCount = 0;
		if (StringUtils.isNotNull(userDriver)) {
			driverLineChart.setVehicleId(userDriver.getId());
			cancelCount = hsmwOrderVehicleRelationMapper.findDriverOrderOnCancleCount(driverLineChart);
		}
		map.put("completeCount",completeCount);
		map.put("cancelCount",cancelCount);

		if (driverLineChart.getFlag() == 1) {
			//  司机填写方量
			List<HomeVolume> reachVolumes = hsmwDriverOrderRecordMapper.findReachVolumeByDriverId(id, driverLineChart.getYear(), driverLineChart.getMonth());
			if(CollectionUtil.isNotEmpty(reachVolumes)){
				// 日期格式化 排序
				reachVolumes.forEach(x -> x.setTime(DateUtil.format(Date.from(x.getEndTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd")));

				Map<String, List<HomeVolume>> reachMap = reachVolumes.stream().collect(Collectors.groupingBy(HomeVolume::getTime));

				// 查询当月多少天
				LocalDate localDate = LocalDate.parse(driverLineChart.getYear() + "-" + driverLineChart.getMonth() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
				//这个月的第一天
				Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
				//这个月的最后一天 下个月的第一天
				Date monthEnd = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
				DateTime endTime = DateUtil.date(monthEnd);
				DateTime startTime = DateUtil.date(monthStart);
				List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(endTime.toJdkDate(), "yyyy-MM-dd"));
				// 司机方量
				dayBetween.forEach(day -> {
					AtomicDouble count = new AtomicDouble();
					cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject();
					jsonObject.put("day", day);
					if (reachMap.get(day) != null) {
						List<HomeVolume> orderList = reachMap.get(day);
						orderList.stream().forEach(x -> {
							if (StrUtil.isNotBlank(x.getForemanVolume())) {
								count.addAndGet(Double.valueOf(x.getForemanVolume()));
							}
						});
					}
					jsonObject.put("count", count);
					reachVolume.add(jsonObject);
				});
			}
			map.put("reachVolume", reachVolume);

		} else if (driverLineChart.getFlag() == 2) {
			List<String> dayBetween = new ArrayList<String>(12);
			for (int i = 1; i <= 12; i++) {
				if(i<10){
					dayBetween.add(driverLineChart.getYear()+"-0"+i);
				}else {
					dayBetween.add(driverLineChart.getYear()+"-"+i);
				}
			}
			List<HomeVolume> homeVolumes = hsmwDriverOrderRecordMapper.findReachVolumeByDriverIdOnYear(driverLineChart.getYear(), driverLineChart.getId());
			homeVolumes.removeAll(Collections.singleton(null));
			if(CollectionUtil.isNotEmpty(homeVolumes)){
				// 日期格式化 排序
				homeVolumes.forEach(x -> x.setTime(DateUtil.format(Date.from(x.getEndTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM")));

				Map<String, List<HomeVolume>> reachMap = homeVolumes.stream().collect(Collectors.groupingBy(HomeVolume::getTime));
				dayBetween.forEach(day -> {
					AtomicDouble count = new AtomicDouble();
					cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject();
					jsonObject.put("day", day);
					if (reachMap.get(day) != null) {
						List<HomeVolume> orderList = reachMap.get(day);
						orderList.stream().forEach(x -> {
							if (StrUtil.isNotBlank(x.getForemanVolume())) {
								count.addAndGet(Double.valueOf(x.getForemanVolume()));
							}
						});
					}
					jsonObject.put("count", count);
					reachVolume.add(jsonObject);
				});
			}
			// 按照年进行分组
			map.put("reachVolume", reachVolume);
		} else {
			List<HomeVolume> reachVolumes = hsmwDriverOrderRecordMapper.findReachVolumeByDriverIdOnSection(id, driverLineChart.getStartTime(), driverLineChart.getEndTime());
			if(CollectionUtil.isNotEmpty(reachVolumes)){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date start = sdf.parse(driverLineChart.getStartTime());
				Date end = sdf.parse(driverLineChart.getEndTime());
				//间隔的日期列表
				DateTime endTime = DateUtil.date(end);
				DateTime startTime = DateUtil.date(start);
				List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(endTime.toJdkDate(), "yyyy-MM-dd"));
				// 日期格式化 排序
				reachVolumes.forEach(x -> x.setTime(DateUtil.format(Date.from(x.getEndTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd")));

				Map<String, List<HomeVolume>> reachMap = reachVolumes.stream().collect(Collectors.groupingBy(HomeVolume::getTime));
				// 司机方量
				dayBetween.forEach(day -> {
					AtomicDouble count = new AtomicDouble();
					cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject();
					jsonObject.put("day", day);
					if (reachMap.get(day) != null) {
						List<HomeVolume> orderList = reachMap.get(day);
						orderList.stream().forEach(x -> {
							if (StrUtil.isNotBlank(x.getForemanVolume())) {
								count.addAndGet(Double.valueOf(x.getForemanVolume()));
							}
						});
					}
					jsonObject.put("count", count);
					reachVolume.add(jsonObject);
				});
			}
			map.put("reachVolume", reachVolume);
		}
		return new DataResponse(map);
	}

	public DataResponse driverSeeSystemMessageByUserId() {

		Map map = new HashMap();

		LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
		if(loginUser == null){
			return new DataResponse(FAIL,"登陆人信息错误，请重新登录");
		}
		String id = loginUser.getId();
		LambdaQueryWrapper<HsmwDriverNews> queryWrapper = new QueryWrapper<HsmwDriverNews>().lambda();
		int systemCount = hsmwDriverNewsService.count(queryWrapper.eq(HsmwDriverNews::getUserId, id).and(wrapper ->wrapper.like(HsmwDriverNews::getMessage, "系统已为您指派订单").or().like(HsmwDriverNews::getMessage, "您的订单已经被取消").or().like(HsmwDriverNews::getMessage, "预计到达时间").or().like(HsmwDriverNews::getMessage, "位置纠错").or().like(HsmwDriverNews::getMessage, "调度").or().like(HsmwDriverNews::getMessage, "到期")).eq(HsmwDriverNews::getAlreadyRead, "0"));
		HsmwDriverNews systemInfo = hsmwDriverNewsService.getOne(new LambdaQueryWrapper<HsmwDriverNews>().eq(HsmwDriverNews::getUserId, id).orderByDesc(HsmwDriverNews::getCreateTime).last("LIMIT 1"));
		map.put("systemCount",systemCount);
		map.put("systemInfo",systemInfo);
		//map.put("customerCount",10);
		//map.put("dispatcherCount","20");
		return new DataResponse(map);
	}

	public DataResponse findDriverScoreRanking() {

		Map map = new HashMap();

		Integer count = hsmwUserDriverMapper.selectCount(new LambdaQueryWrapper<>());
		List<HsmwUserDriver> userDrivers = null;
		List<HsmwDriverOrderRecord> hsmwDriverOrderRecords = null;
		if(count > 50){
			userDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().orderByDesc(HsmwUserDriver::getScore).last("LIMIT 7"));

			hsmwDriverOrderRecords = hsmwDriverOrderRecordService.findDriverCountAndDriverId("1");

		}else {
			 userDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().orderByDesc(HsmwUserDriver::getScore));

			 hsmwDriverOrderRecords = hsmwDriverOrderRecordService.findDriverCountAndDriverId("2");
		}
		List<DriverInfoDTO> driverInfoDTOS = new ArrayList<>();

		List<DriverInfoDTO> driverInfo = new ArrayList<>();
		if(CollectionUtil.isNotEmpty(userDrivers)){
			for (HsmwUserDriver userDriver : userDrivers) {
				HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(userDriver.getUserId());
				if(hsmwDriverUser != null){
					DriverInfoDTO driverInfoDTO = new DriverInfoDTO();
					driverInfoDTO.setDriverName(hsmwDriverUser.getName());
					driverInfoDTO.setScores(userDriver.getScore());
					driverInfoDTO.setHeadProfile(userDriver.getMyPicture());
					driverInfoDTOS.add(driverInfoDTO);
				}
			}
		}
		if(CollectionUtil.isNotEmpty(hsmwDriverOrderRecords)){
			for (HsmwDriverOrderRecord hsmwDriverOrderRecord : hsmwDriverOrderRecords) {
				if(StringUtils.isNotBlank(hsmwDriverOrderRecord.getDriverId())){
					HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(hsmwDriverOrderRecord.getDriverId());
					if(StringUtils.isNotNull(userDriver)){
						HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(userDriver.getUserId());
						if(hsmwDriverUser != null){
							DriverInfoDTO driverInfoDTO = new DriverInfoDTO();
							driverInfoDTO.setDriverName(hsmwDriverUser.getName());
							driverInfoDTO.setScores(hsmwDriverOrderRecord.getNum());
							driverInfoDTO.setHeadProfile(userDriver.getMyPicture());
							driverInfo.add(driverInfoDTO);
						}
					}
				}
			}
		}
		map.put("score",driverInfoDTOS);
		map.put("orderCount",driverInfo);
		return new DataResponse(map);
	}

    public void getAllDriverInfo(String ownCompanyId) {



    }

	public IPage<HsmwHelpCenter> findHelpCenterList(IPage page, HsmwHelpCenter hsmwHelpCenter) {
		LoginUser currentUserInfo = currentHsmwUserUtils.getCurrentUserInfo();

		String key = "driver:search:"+currentUserInfo.getId();

		LambdaQueryWrapper<HsmwHelpCenter> queryWrapper = new LambdaQueryWrapper<>();
		if(StringUtils.isNotBlank(hsmwHelpCenter.getTitle())){
			queryWrapper
					.and(wrapper -> wrapper.like(HsmwHelpCenter::getTitle,hsmwHelpCenter.getTitle())
					.or()
					.like(HsmwHelpCenter::getRemark, hsmwHelpCenter.getTitle()));
			redisTemplate.opsForZSet().add(key,hsmwHelpCenter.getTitle(),System.currentTimeMillis());
			insertSearchSort(key,hsmwHelpCenter.getTitle());
		}
		if(StringUtils.isNotBlank(hsmwHelpCenter.getType())){
			queryWrapper.eq(HsmwHelpCenter::getType,hsmwHelpCenter.getType());
		}
		//queryWrapper.eq(HsmwHelpCenter::getUrl,"1");
		IPage<HsmwHelpCenter> iPage = hsmwHelpCenterMapper.selectPage(page,queryWrapper.orderByDesc(HsmwHelpCenter::getCreateTime));
		return iPage;
	}




	public void insertSearchSort(String key,String value){
		//阈值-历史最多5个
		long top  = 5;
		// 拿到存入Redis里数据的唯一分值
		Double score = redisTemplate.opsForZSet().score(key, value);
		//检索是否有旧记录  1.无则插入记录值  2.有则删除 再次插入
		if(null != score){
			//删除旧的
			redisTemplate.opsForZSet().remove(key,value);
		}
		//加入新的记录，设置当前时间戳为分数score
		redisTemplate.opsForZSet().add(key,value,System.currentTimeMillis());
		//获取总记录数
		Long aLong = redisTemplate.opsForZSet().zCard(key);
		if(aLong > top){
			//获取阈值200之后的记录  (0,1] 并移除
			redisTemplate.opsForZSet().removeRange(key,0,aLong-top-1);
		}

	}


	public DataResponse updateHelpCenterNum(String id,String driverId,String params) {

		if(StringUtils.isBlank(params)){
			return new DataResponse(FAIL,"传递参数错误");
		}
		HsmwDriverUser userInfo = currentHsmwUserUtils.getCurrentDriverUserInfo();
		HsmwHelpCenter hsmwHelpCenter = hsmwHelpCenterMapper.selectById(id);
		HsmwHelpAvaliableInfo hsmwHelpAvaliableInfo = new HsmwHelpAvaliableInfo();
		if(StringUtils.equals("1",params)){
			hsmwHelpCenter.setAvailNumber(hsmwHelpCenter.getAvailNumber() + 1);
			hsmwHelpAvaliableInfo.setAvailableFlag(CommonConstants.YES);
		}else if(StringUtils.equals("2",params)) {
			hsmwHelpCenter.setUnAvailNumber(hsmwHelpCenter.getUnAvailNumber() + 1);
			hsmwHelpAvaliableInfo.setAvailableFlag(CommonConstants.NO);
		}else {
			hsmwHelpCenter.setClickCount(hsmwHelpCenter.getClickCount() + 1);
		}
		if(StringUtils.equals("1",params) || StringUtils.equals("2",params)){
			hsmwHelpAvaliableInfo.setHelpId(id);
			hsmwHelpAvaliableInfo.setRemark("司机");
			hsmwHelpAvaliableInfo.setUserId(userInfo.getId());
			hsmwHelpAvaliableInfo.setDriverId(driverId);
			hsmwHelpAvaliableInfoMapper.insert(hsmwHelpAvaliableInfo);
		}
		return new DataResponse(hsmwHelpCenterMapper.updateById(hsmwHelpCenter));
	}

	public Map findDriverVolumesInfo(String id, String month) {
		Map<String,Object> map = new HashMap();
		// 结算方量
		String volumes = hsmwDriverOrderRecordMapper.findSettlementVolumesById(id,month);
		if(volumes ==null){
			volumes = "0";
		}
		map.put("volumes",volumes);
		// 空跑次数
		Long  runCount = hsmwRunSprintRecordService.findDriverRunSoringCount(id,month);
		map.put("runCount",runCount);
		// 挪泵次数
		Long moveCount = hsmwOrderBalanceMapper.findMoveCountById(id,month);
		map.put("moveCount",moveCount);

		HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(id);
		if(userDriver != null){
			HsmwLeasingCompany leasingCompany = hsmwLeasingCompanyService.getById(userDriver.getOwnCompanyId());
			if(leasingCompany != null && StringUtils.isNotBlank(leasingCompany.getName())){
				map.put("leasingCompanyName",leasingCompany.getName());
			}
		}
		return map;
	}

	public Object saveOrUpdateDriverComplian(HsmwDriverComplain hsmwDriverComplain) {

		LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();

		if(StringUtils.isNotBlank(hsmwDriverComplain.getId())){

			hsmwDriverComplain.setComplainName(loginUser.getName());
			hsmwDriverComplain.setComplainPhone(loginUser.getUsername());
			if (CollectionUtil.isNotEmpty(hsmwDriverComplain.getPicList())) {
				List<HsmwPicture> pictures = new ArrayList<>();
				List<HashMap> picList = hsmwDriverComplain.getPicList();
				if (null != picList && picList.size() > 0) {
					for (HashMap<String, String> pic : picList) {
						HsmwPicture temp = new HsmwPicture();
						temp.setPicPath(pic.get("picPath"));
						temp.setPicRealPath(pic.get("realPath"));
						temp.setPortId(hsmwDriverComplain.getId());
						temp.setCreateTime(LocalDateTime.now());
						temp.setPicType(PicTypeEnum.DRIVER_COMPLAIN.getValue());
						pictures.add(temp);
					}
				}
				hsmwPictureService.saveBatch(pictures);
			}

			return hsmwDriverComplainMapper.updateById(hsmwDriverComplain);
		}else {

			hsmwDriverComplain.setComplainName(loginUser.getName());
			hsmwDriverComplain.setComplainPhone(loginUser.getUsername());
			int insert = hsmwDriverComplainMapper.insert(hsmwDriverComplain);
			if (CollectionUtil.isNotEmpty(hsmwDriverComplain.getPicList())) {
				List<HsmwPicture> pictures = new ArrayList<>();
				List<HashMap> picList = hsmwDriverComplain.getPicList();
				if (null != picList && picList.size() > 0) {
					for (HashMap<String, String> pic : picList) {
						HsmwPicture temp = new HsmwPicture();
						temp.setPicPath(pic.get("picPath"));
						temp.setPicRealPath(pic.get("realPath"));
						temp.setPortId(hsmwDriverComplain.getId());
						temp.setCreateTime(LocalDateTime.now());
						temp.setPicType(PicTypeEnum.DRIVER_COMPLAIN.getValue());
						pictures.add(temp);
					}
				}
				hsmwPictureService.saveBatch(pictures);
			}
			return insert;
		}
	}

	public DataResponse findDriverComplianList(HsmwDriverComplain hsmwDriverComplain) {
		if(hsmwDriverComplain == null){
			return new DataResponse(FAIL,"传递参数不可为空");
		}

		LambdaQueryWrapper<HsmwDriverComplain> queryWrapper = new LambdaQueryWrapper<>();
		if(StringUtils.isNotBlank(hsmwDriverComplain.getDriverId())){
			queryWrapper.eq(HsmwDriverComplain::getDriverId,hsmwDriverComplain.getDriverId());
		}
		if(StringUtils.isNotBlank(hsmwDriverComplain.getComplainName())){
			queryWrapper.like(HsmwDriverComplain::getComplainName,hsmwDriverComplain.getComplainName());
		}
		if(StringUtils.isNotBlank(hsmwDriverComplain.getComplainPhone())){
			queryWrapper.like(HsmwDriverComplain::getComplainPhone,hsmwDriverComplain.getComplainPhone());
		}
		if(StringUtils.isNotBlank(hsmwDriverComplain.getComplainType())){
			queryWrapper.like(HsmwDriverComplain::getComplainType,hsmwDriverComplain.getComplainType());
		}
		if(StringUtils.isNotBlank(hsmwDriverComplain.getComplainStatus())){
			queryWrapper.like(HsmwDriverComplain::getComplainStatus,hsmwDriverComplain.getComplainStatus());
		}
		List<HsmwDriverComplain> hsmwDriverComplains = hsmwDriverComplainMapper.selectList(queryWrapper);

		return new DataResponse(hsmwDriverComplains);
	}

	public QueryOrderDetailVO queryOrderInfoById(String id,String flag) {
		if(StringUtils.equals("线下",flag)){
			QueryOrderDetailVO queryOrderDetailVO = new QueryOrderDetailVO();
			HsmwDriverOrderRecord hsmwDriverOrderRecord = hsmwDriverOrderRecordMapper.selectById(id);
			queryOrderDetailVO.setOrderId(hsmwDriverOrderRecord.getOrderId());
			queryOrderDetailVO.setCompleteVolume(hsmwDriverOrderRecord.getRealVolume());
			queryOrderDetailVO.setCompleteTime(hsmwDriverOrderRecord.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
			queryOrderDetailVO.setItemName(hsmwDriverOrderRecord.getItemName());
			queryOrderDetailVO.setItemPosition(hsmwDriverOrderRecord.getItemPosition());
			queryOrderDetailVO.setConstructionUnitName(hsmwDriverOrderRecord.getConstructionUnitName());
			queryOrderDetailVO.setMoveCount(hsmwDriverOrderRecord.getMovePumpCount());
			queryOrderDetailVO.setConstructionPosition(hsmwDriverOrderRecord.getConstructionPosition());
			queryOrderDetailVO.setGrabbTime(hsmwDriverOrderRecord.getStartWorkTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
			queryOrderDetailVO.setChassisKilometers(hsmwDriverOrderRecord.getChassisKilometers());
			queryOrderDetailVO.setWorkTime(hsmwDriverOrderRecord.getWorkTime());
			return queryOrderDetailVO;
		}else {
			HashMap map = new HashMap();
			QueryOrderDetailVO queryOrderDetailVO = hsmwUserDriverMapper.queryOrderInfoById(id);
			map.put("orderId",queryOrderDetailVO.getMainOrderId());
			List<VehicleStatisticsVO> vehicleStatisticsVOS = hsmwOrderVehicleRequestMapper.findVehicleInfoByOrderId(queryOrderDetailVO.getMainOrderId());
			if(CollectionUtil.isNotEmpty(vehicleStatisticsVOS)){
				queryOrderDetailVO.setVehicleStatisticsVOS(vehicleStatisticsVOS);
			}
			List<HsmwConstructionPosition> ps= hsmwOrderMapper.selectPositionsByOrderId(map);
			if(CollectionUtil.isNotEmpty(ps)){
				queryOrderDetailVO.setHsmwConstructionPositions(ps);
			}
			return queryOrderDetailVO;
		}

	}

	public List<HsmwItem> queryDriverCompanyForItemByDriverId(String id,String locate) {

		List<HsmwItem> list = new ArrayList<>();
		HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(id);
		if (StringUtils.isNotNull(hsmwUserDriver) && StringUtils.isNotBlank(hsmwUserDriver.getOwnCompanyId())) {
			list = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>().eq(HsmwItem::getVehicleUnitId, hsmwUserDriver.getOwnCompanyId()));
			if (CollectionUtil.isNotEmpty(list)) {
				for (HsmwItem hsmwItem : list) {
					HashMap calculateParam = new HashMap();
					calculateParam.put("origin", locate);
					calculateParam.put("destination", hsmwItem.getLng() + "," + hsmwItem.getLat());
					Long mapTimeAndDistance = GaoDeInfoUtils.calculateDistance(calculateParam);
					Long distence = mapTimeAndDistance / 1000;
					hsmwItem.setDistance(StringUtils.isNull(distence) ? 0L : distence);
					double volume = hsmwItemService.sumDriverVolumeByItemId(hsmwItem.getId());
					hsmwItem.setVolumeSum(volume);
				}
			}
		}
		return list;
	}

	public List<HsmwHelpCenter> selectHelpInfoList() {
		return  hsmwUserDriverMapper.selectHelpInfoList();
	}

	public List<HsmwHelpCenter> selectTopHelpInfoList() {
		return  hsmwUserDriverMapper.selectTopHelpInfoList();
	}


	public DataResponse queryHelpCenterInfoByHelpId(String id, String helpId) {

		HsmwHelpAvaliableInfo hsmwHelpAvaliableInfo = hsmwHelpAvaliableInfoMapper.selectOne(new LambdaQueryWrapper<HsmwHelpAvaliableInfo>().eq(HsmwHelpAvaliableInfo::getDriverId, id)
				.eq(HsmwHelpAvaliableInfo::getHelpId, helpId)
		);
		Map map = new HashMap();
		if(hsmwHelpAvaliableInfo != null){
			map.put("status",hsmwHelpAvaliableInfo.getAvailableFlag());
		}else {
			map.put("status",null);
		}
		return new DataResponse(SUCCESS,map);
	}


}
